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

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

//希望能帮到大家,省下一些时间.
  • 11
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值