您的位置:首页 > 编程语言 > C语言/C++

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

2016-12-01 22:28 453 查看

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

一次C++作业题, 搞了很久弄明白了, 虽然成功了, 但VS2015依旧有红线提示错误, 不过不影响编译、运行, 这似乎是VS自身的一个BUG。

解决:

友元类方法小结:

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;
}

//希望能帮到大家,省下一些时间.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++
相关文章推荐