[英]How to initialize a class member data with other member data of this class ?
我有A和B类。B是A的成员。我需要用A的其他数据成员初始化B。
class A;
class B
{
public:
B(A& a){cout << "B constr is run \n";}
};
class A
{
public:
A(){}
void initB(A& a){b(a); cout << "A call init B \n"; }
private:
// other members ...
B b;
};
int main()
{
A a;
a.initB(a);
}
我收到编译错误:
classIns.cpp: In constructor âA::A()â:
classIns.cpp:14: error: no matching function for call to âB::B()â
classIns.cpp:8: note: candidates are: B::B(A&)
classIns.cpp:6: note: B::B(const B&)
classIns.cpp: In member function âvoid A::initB(A&)â:
classIns.cpp:16: error: no match for call to â(B) (A&)â
为什么A(){}需要调用B :: B()?
如何用A的其他数据成员初始化B?
谢谢
B
没有默认的构造函数,这意味着您必须在A
的ctor中对其进行初始化。
struct A {
A() : b(*this) {}
private:
B b;
};
每当您想到使用init
的成员时,您就可能做错了。 构造函数完成后,对象应始终有效。
像这样 :
void initB(A& a){
b = B(a);
cout << "A call init B \n";
}
当然,类B需要一个默认的构造函数,以及一个引用了A类型对象的副本构造函数。
您可以在A构造函数中使用初始化链:
class B
{
public:
B(Type1 x, Type2 y)
{
}
void init(Type1 x, Type2 y) { ........}
};
class A
{
public:
A() : Amember1(), Amember2(), b(Amember1, Amember2) {}
private:
Type1 Amember1;
.....
B b;
};
但是您不能在initB
方法中调用B构造函数,因为b已经被构造。 您可以对A数据使用B::init()
方法,例如:
void A::initB(A& a){ b.init(a.Amember1, a.Amember2); cout << "A call init B \n"; }
为什么A(){}需要调用B :: B()?
因为A具有数据成员B,所以在创建A类的实例时需要对其进行初始化。 在您的情况下,b使用默认的B c'tor初始化。
由于您正在为B指定构造函数
public:
B(A& a){cout << "B constr is run \n";}
默认构造函数:
B(){}
不是由编译器自动生成的。 所以它抱怨。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.