gpt4 book ai didi

C++ OOP 基础知识(将对象分配为成员)

转载 作者:太空狗 更新时间:2023-10-29 23:47:50 26 4
gpt4 key购买 nike

我是一名 PHP 开发人员,正在尝试编写一些 C++。

我在将一个对象指定为另一个对象的属性时遇到了问题。在 PHP 中,我会这样写:

class A {
public $b;
}
class B {

}

$a = new A;
$a->b = new B;

我如何在 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);

我做错了什么?

最佳答案

只需这样做:

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();
}

您实际上不需要单独创建 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
}

关于C++ OOP 基础知识(将对象分配为成员),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3696275/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com