我现在正在编写C++代码进行数学计算。然而,似乎不可能使用普通构造函数来初始化类成员。
为了实例化,首先调用A的构造函数。到那时,p和q只是声明,因此p和q也没有被实例化。因此,我应该能够调用B的构造函数来实例化它们。对吗?我认为我的C++类理解可能有误,所以在这里发帖确认。
为了实例化,首先调用A的构造函数。到那时,p和q只是声明,因此p和q也没有被实例化。因此,我应该能够调用B的构造函数来实例化它们。对吗?我认为我的C++类理解可能有误,所以在这里发帖确认。
class B{
// default constructor and copy constructor
}
class A{
private:
B p;
B q;
public:
explicit A(int _p, int _q);
}
// implementation
A::A(int _p, int _q){
// some computing goes here so I can't apply
// A::A(int _p, int _q):p{_p}, q{_q}
// p = B{_p}
// q = B{_q}
// this works
p{_p}; // Can't compile.
q{_q}; // What's wrong with this?
}