“friend声明友元函数,友元函数却依旧无法访问该类的私有属性”的解决方法

来源:互联网 发布:windows 10下崩溃绿屏 编辑:程序博客网 时间:2024/05/16 09:55

背景:这次是一次C++作业题,很诡异,搞了很久弄明白了,虽然成功了,但VS2015依旧有红线提示错误,不过不影响编译、运行。
解决:
友元类方法总结:1、包含声明”friend”的类,必须在((包含其声明的友元函数)的那个类)之前事先声明下————因为在Employer类中用到”Employee&”,不然无法访问该引用的私有成员。
2、被声明为友元的函数,必须在类内声明,然后在将其声明为友元函数的类的后面定义。
3、还有一个我个人犯的弱智错误——在声明友元函数时,忘记加该函数的作用域了。。。。

作业代码如下:#include < iostream >

include < string >

using namespace std;

class Employee;

class Employer
{
public:
Employer(string a) {
Name = a;
};
void editEmployee(Employee & person, double salary, string post);
private:
string Name;
};

class Employee {
public:Employee(int a, string b, double c, string d) {
ID = a;
Name = b;
Salary = c;
Post = d;
}
friend void Employer::editEmployee(Employee & person, double salary, string post);
void printInf() {
cout << “ID:” << ID << “\t” << “Name:” << Name << “\t” << “Salary:” << Salary << “\t” << “Post:” << Post << endl;
}
protected:
private:
int ID;
string Name;
double Salary;
string Post;
};

void Employer::editEmployee(Employee & person, double salary, string post) {
person.Salary = salary;
person.Post = post;
};

int main()
{
Employee sb(22, “abc”, 1.23, “a”);
cout << “Previous Information :” << endl;
sb.printInf();
Employer boss(“BidBoss”);
cout << “Updated Information :” << endl;
boss.editEmployee(sb, 12.3, “b”);
sb.printInf();
return 0;
}

//希望能帮到大家,省下一些时间.

0 0
原创粉丝点击