Code::blocks显示“非静态数据成员的无效使用”。为什么会出现这个错误?
class counter {
public:
counter()=default; //default contructor
friend void upg(){++val;} //function that increases "val" by 1
private:
int val=0;
};发布于 2015-04-17 20:49:38
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++; }发布于 2015-04-17 21:25:27
我想你不明白什么是好友功能。
让我们创建一个包含一个好友函数、一个常规函数和一个方法的对象:
#include <set>
#include <utility>
class counter {
public:
void method_inc();
friend void friend_inc(counter & c);
private:
int val = 0;
};
void counter::method_inc() {
this->val++;
void friend_inc(counter & c) {
c.val++;
}
void nonfriend_inc(counter & c) {
c.val++; // Error: val is private.
}
int main() {
counter c;
c.method_inc();
friend_inc(c);
nonfriend_inc(c);
}让我们来讨论一下我们的函数:
this,允许它访问被调用的对象。在这种情况下,c.member_inc().nonfriend_inc()中的c必须具有它正在使用的对象的参数。但它也无法构建,因为counter::val是私有的,而且它不是朋友,function.friend_inc()也没有隐式的this。但因为它是class counter的友好函数,所以它可以访问该对象的私有成员。https://stackoverflow.com/questions/29699661
复制相似问题