【发布时间】:2011-10-29 17:02:05
【问题描述】:
我有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 ?
谢谢
【问题讨论】:
-
为什么有五个答案而没有“初始化列表”的实例
标签: c++ class object constructor