我有 2 个类,如下所示:
class A : public C
{
void Init();
};
class B : public C
{
int a = 3;
};
我如何访问 A 类中 B 类的成员?
class A::Init()
{
class B. a ???
}
我有 2 个类,如下所示:
class A : public C
{
void Init();
};
class B : public C
{
int a = 3;
};
我如何访问 A 类中 B 类的成员?
class A::Init()
{
class B. a ???
}
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.
如果您想将 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;
您必须创建一个实例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;
}
你也可以尝试在你的类中添加静态函数。但我不确定这是否是你要找的。
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;
};