无效使用非静态数据成员 [英] invalid use of non-static data member

查看:198
本文介绍了无效使用非静态数据成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于像这样的代码:

class foo {
  protected:
    int a;
  public:
    class bar {
      public:
        int getA() {return a;}   // ERROR
    };
    foo()
      : a (p->param)
};

我收到此错误:

 invalid use of non-static data member 'foo::a'

目前,在 foo 的构造函数中初始化变量 a

currently the variable a is initialized in the constructor of foo.

如果我使它静态,则说:

if I make it static, then it says:

 error: 'int foo::a' is a static data member; it can only be initialized at its definition

但是我想传递一个值到 a
那么是什么解决方案?

However I want to pass a value to a in the constructor. What is the solution then?

推荐答案

在C ++中,本质上不属于包含类的任何实例。因此 bar :: getA 没有 foo 的任何特定实例,其 code>它可以返回。我猜你想要的是什么样的:

In C++, unlike (say) Java, an instance of a nested class doesn't intrinsically belong to any instance of the enclosing class. So bar::getA doesn't have any specific instance of foo whose a it can be returning. I'm guessing that what you want is something like:

    class bar {
      private:
        foo * const owner;
      public:
        bar(foo & owner) : owner(&owner) { }
        int getA() {return owner->a;}
    };

但是即使这样,你可能需要做一些修改,因为在C ++ 11,不像(再次说)Java,嵌套类没有对它的封闭类的特殊访问,所以它不能看到 protected member a 。这将取决于您的编译器版本。

But even for this you may have to make some changes, because in versions of C++ before C++11, unlike (again, say) Java, a nested class has no special access to its enclosing class, so it can't see the protected member a. This will depend on your compiler version. (Hat-tip to Ken Wayne VanderLinde for pointing out that C++11 has changed this.)

这篇关于无效使用非静态数据成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆