我是一个PHP开发人员,试图编写一些C++.
我将对象指定为另一个对象的属性时遇到了麻烦.在PHP中,我写这个:
class A {
public $b;
}
class B {
}
$a = new A;
$a->b = new B;
Run Code Online (Sandbox Code Playgroud)
我怎么用C++做到这一点?我到目前为止得到了这个:
class A {
B b;
public:
void setB(&B);
};
class B {
};
void A::setB(B &b)
{
this->b = b;
};
A * a = new A();
B * b = new B();
a->setB(b);
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
这样做:
class B
{
};
class A
{
B b;
};
int main()
{
A anA; // creates an A. With an internal member of type B called b.
// If you want a pointer (ie using new.
// Then put it in a smart pointer.
std::auto_ptr<A> aPtr = new A();
}
Run Code Online (Sandbox Code Playgroud)
您实际上不需要单独创建B. B b是类的一部分,在创建A对象时自动创建(使用默认构造函数).分别创建两个对象然后组合它们是一个坏主意.
如果要在构造时将某些参数传递给B对象.通过为A调用B的构造函数创建一个构造函数,这很容易做到:
class B
{
public:
B(std::string const& data) // The B type takes a string as it is constructed.
:myData(data) // Store the input data in a member variable.
{}
private:
std::string myData;
};
class A
{
public:
A(std::string const& bData) // parameter passed to A constructor
:b(bData); // Forward this parameter to `b` constructor (see above)
{}
private:
B b;
};
int main()
{
A a("Hi there"); // "Hi there" now stored in a.b.myData
}
Run Code Online (Sandbox Code Playgroud)