注册 登录
编程论坛 C++教室

这里为什么会报错?

青蝶 发布于 2018-10-02 21:15, 1153 次点击
#include <iostream>
using namespace std;
class MyInt
{
    int nVal;
    public:
    MyInt( int n) { nVal = n ;}
    MyInt & operator - (const int x){
        nVal-=x;
        return *this;
    }
    friend int Inc(MyInt My){//如果不加"friend",下面红色的语句会报错
        return My.nVal+1;
    }
};
int Inc(int n) {
    return n + 1;
}
int main () {
    int n;
    while(cin >>n) {
        MyInt objInt(n);
        objInt-2-1-3;
        cout << Inc(objInt);
        cout <<",";
        objInt-2-1;
        cout << Inc(objInt) << endl;
    }
    return 0;
}
   
求大佬解释一下为什么会这样?
还有我觉得并没有用到友元,有没有其他修改的办法?   
        
1 回复
#2
Jonny02012018-10-02 21:35
因为 nVal 是私用的, 不对外公开的
而 friend 的作用就是让 nVal 对 friend 函数公开
外界直接访问一个私用的变量是不可以通过编译的
1