Code :: blocks表示“非静态数据成员的使用无效”。为什么会出现这个错误?
class counter {
public:
counter()=default; //default contructor
friend void upg(){++val;} //function that increases "val" by 1
private:
int val=0;
};
答案 0 :(得分:4)
upg()
不是会员功能。因此,如果没有val
的实例,则无法访问counter
。这可以编译,虽然它可能没有多大意义:
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++; }
答案 1 :(得分:1)
让我们创建一个具有友元函数,常规函数和方法的对象:
#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
中的c.member_inc()
。
函数nonfriend_inc()
必须包含它正在使用的对象的参数。但它也无法构建,因为counter::val
是私有的,而且它不是朋友的功能。
函数friend_inc()
也没有隐式this
。但因为它是class counter
的友方函数,所以它可以访问该对象的私有成员。