0

ヘッダー ファイルでフレンド関数を宣言し、.cpp ファイルで定義しましたが、コンパイルすると、変数が「このスコープで宣言されていません」と表示されます。関数がクラスのフレンドとしてラベル付けされている場合、その関数はそのクラスのすべてのメンバーに直接アクセスできると理解していますが、なぜこのエラーが発生するのでしょうか?

私の .h ファイル:

#ifndef EMPLOYEE_H
#define EMPLOYEE_H

#include<string>
using namespace std;

class Employee
{
  friend void SetSalary(Employee& emp2);

 private:

  string name;
  const long officeNo;
  const long empID;
  int deptNo;
  char empPosition;
  int yearOfExp;
  float salary;
  static int totalEmps;
  static int nextEmpID;
  static int nextOfficeNo;

 public:
  Employee();
  ~Employee();
  Employee(string theName, int theDeptNo, char theEmpPosition, int theYearofExp);
  void Print() const;
  void GetInfo();
};

#endif

my.cpp ファイルの関数

void SetSalary(Employee& emp2)
{

  while (empPosition == 'E')
    {
      if (yearOfExp < 2)
        salary = 50000;
      else
        salary = 55000;
    }
}

注: 私の Main.cpp では、オブジェクト 'emp2' を作成しています。これは、パラメーターとして関数に渡されます。

4

1 に答える 1

4

empPositionyearOfExpおよびクラスsalaryのメンバーであるEmployeeため、必要です

while (emp2.empPosition == 'E') ....
//     ^^^^

yearOfExpおよびを含む式についても同様ですsalaryfriend関数は非メンバー関数であるため、そのクラスのインスタンス (emp2この場合) を介して、フレンドであるクラスのデータ メンバーにのみアクセスできます。

于 2013-10-12T16:17:01.930 に答える