Code::blocks 说“非静态数据成员的使用无效”。为什么会出现此错误?
class counter {
public:
counter()=default; //default contructor
friend void upg(){++val;} //function that increases "val" by 1
private:
int val=0;
};
最佳答案
upg()
不是成员函数。因此,如果没有 counter
的实例,它就无法访问 val
。这会编译,虽然它可能没有多大意义:
friend void upg() { counter c; c.val++; }
更好的解决方案可能是使 upg()
成为成员,
class counter
{
public:
counter()=default; // some pointless code "documentation"
void upg(){ ++val; } //function that increases "val" by 1
private:
int val=0;
};
或者,如果你真的需要一个非成员,给它一个counter
参数:
friend void upg(counter& c) { c.val++; }
关于C++//非静态数据成员的无效使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29699661/