“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; } //希望能帮到大家,省下一些时间.
相关文章推荐
- VC6.0中友元函数无法访问类私有成员的解决办法
- VC6_0中友元函数无法访问类私有成员的解决办法---VC6_0的经典bug(转)
- VC6.0中友元函数无法访问类私有成员的解决办法(VC6.0的bug)
- VC6.0中友元函数无法访问类私有成员的解决办法
- VC6.0中友元函数无法访问类私有成员的解决办法
- VC6.0中友元函数无法访问类私有成员的解决办法
- VC6.0中友元函数无法访问类私有成员的解决办法-------VC6.0的bug
- VC6.0中友元函数无法访问类私有成员的解决办法
- VC6.0中友元函数无法访问类私有成员的解决办法
- TypeError: Error #1009: 无法访问空对象引用的属性或方法。(解决)
- mx:states包含mx:AddChild 在切换时提示错误"TypeError: Error #1009: 无法访问空对象引用的属性或方法"的解决方法
- VC6.0中友元函数无法访问类私有成员的解决办法
- VC6_0中友元函数无法访问类私有成员的解决办法---VC6_0的经典bug(转)
- VC6.0中友元函数无法访问类私有成员的解决办法
- VC6.0中友元函数无法访问类私有成员的解决办法-------VC6.0的bug
- VC6.0中友元函数无法访问类私有成员的解决办法
- error C2248: “CObject::CObject”: 无法访问 private 成员(在“CObject”类中声明)----解决方法
- Error #1009: 无法访问空对象引用的属性或方法 --问过的个问题 解决了 记录下
- 局域网中无法/无权访问的解决方法
- HTTP 错误 403.1 - 禁止访问:执行访问被拒绝。 解决方法该页无法显示