0

我有 2 个类,如下所示:

class A : public C
{
void Init();
};

class B : public C
{
int a = 3;
};

我如何访问 A 类中 B 类的成员?

class A::Init()
{
 class B. a  ???
}
4

4 回答 4

2

Perhaps you want a static member, which you can access without an object of type B?

class B : public C
{
public:
    static const int a = 3;
};

Now you can access it from anywhere (including your A::Init function) as B::a.

If that's not what you want, then please clarify the question.

于 2013-04-03T14:44:10.663 回答
1

如果您想将 B 类的“属性”作为全局访问,而不是特定对象,则在此类中将变量设为静态

class B : public C
{
public:
    static const int a = 0;
};

并使用B::a


或者:

class A{
public:
    void init(){
        static int a2 = 0;
        a1=a2;
    }
    int a(){return a1;}
private:
    static int a1;
};
int A::a1=0;
于 2013-04-03T14:46:26.723 回答
1

您必须创建一个实例class B并声明变量 public

class B : public C
{
    public:
    int a=3;//Data member initializer is not allowed in Visual Studio 2012, only the newest GCC
};

void A::Init()
{
 B b;
 b.a= 0;
}

如果您不想创建 的实例class B,请声明变量 static

class B : public C
{
public:
    static int a = 3;
};

然后像这样访问它:

void A::Init()
{
   B::a=0;
}
于 2013-04-03T14:30:08.747 回答
0

你也可以尝试在你的类中添加静态函数。但我不确定这是否是你要找的。

class B: public C
{
public:
    static int GetA(void) {return a;}
private:
    static int a;
};
int B::a = 4;

class A: public C
{
public:
    void Init()
    {
    std::cout<<"Val of A "<<B::GetA()<<std::endl;
    }

private:
    int b;
};
于 2013-04-04T08:35:45.020 回答