2013-10-12 66 views
0

我已经在我的头文件中声明了一个好友函数,并在我的.cpp文件中定义了它,但是当我编译时,我被告知变量没有在此范围内声明。这是我的理解,当一个函数被标记为一个类的朋友时,该函数可以直接访问该类的所有成员,那么为什么我会得到这个错误?我的朋友函数没有执行

我.h文件中:在my.cpp文件

#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 

功能

void SetSalary(Employee& emp2) 
{ 

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

注:在我Main.cpp的,我创建一个对象EMP2“。这是作为参数传递给函数的。

回答

4

empPositionyearOfExpsalaryEmployee类的成员,所以你需要

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

,同样涉及yearOfExpsalary表达。 friend函数是非成员函数,因此它们只能通过该类的一个实例(本例中为emp2)访问他们是朋友的类的数据成员。

+0

哇......在标题和.cpp之间来回移动之后,我对此没有任何意见。我应该注意到,昨晚。 – Kevin