我在我的头文件中声明了一个友元函数,并在我的 .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”。这将作为参数传递给函数。
最佳答案
empPosition
、yearOfExp
和 salary
是 Employee
类的成员,因此您需要
while (emp2.empPosition == 'E') ....
// ^^^^
对于涉及 yearOfExp
和 salary
的表达式也是如此。 friend
函数是非成员函数,因此它们只能通过该类的实例(在本例中为 emp2
)访问它们是友元的类的数据成员。
关于c++ - 我的 friend 功能没有执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19336430/