C ++ //无效数据成员的使用无效

时间:2015-04-17 12:47:39

标签: c++

Code :: blocks表示“非静态数据成员的使用无效”。为什么会出现这个错误?

class counter {

public:
counter()=default;      //default contructor

friend void upg(){++val;}  //function that increases "val" by 1

private:
    int val=0;

};

2 个答案:

答案 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);
}

让我们谈谈我们的职能:

  1. 该方法具有隐式this,允许它访问调用它的对象。在这种情况下,这将是c中的c.member_inc()

  2. 函数nonfriend_inc()必须包含它正在使用的对象的参数。但它也无法构建,因为counter::val是私有的,而且它不是朋友的功能。

  3. 函数friend_inc()也没有隐式this。但因为它是class counter的友方函数,所以它可以访问该对象的私有成员。