gpt4 book ai didi

c++ - 在 C++ 中创建另一个类的多个类对象成员

转载 作者:太空宇宙 更新时间:2023-11-04 13:08:46 24 4
gpt4 key购买 nike

我在将多个类对象作为另一个类的成员时遇到了麻烦。更具体地说:假设我们有 2 个类,A 和 B,并且 A 类是嵌套的。我希望主函数有一个包含 3 个 B 类对象的数组。第一个对象将有 2 个 A 类对象,第二个对象将有 5 个 A 类对象,第三个对象将有 7 个 A 类对象。如何我可以这样做吗?以下是我的一个想法:

Class A{

private:
int variable;

public:
A(){
cout<< A created! <<endl;
}

~A(){
cout<< A destructed! <<endl;
}

};


Class B{

private:
A array[6]; //It will always create 6 elements of class A...

public:
B(){
cout<< B created! <<endl;
}

~B(){
cout<< B destructed! <<endl;
}

};

int main(){

B* array[3];

for (i = 0 ; i <= 2 ; i++)
{
array[i] = new B(); //Every B element in array have 6 elements of class A
}

}

提前致谢!

最佳答案

如果您不能使用 vector ..(您应该使用)..这里是一个工作示例,显示了您想要对数组和手动内存管理执行的操作。 https://ideone.com/KihmON

注意:这里没有错误处理。如果这是您的程序,new 不太可能会失败,但对于较大的对象,它可能会失败。如果您在 delete 语句之前在 main 中抛出错误,这些对象将永远不会被删除。这就是为什么首选 vector 的原因,在出现错误的情况下,无论如何都会在它离开作用域时将其清除。

#include <iostream>

class A
{
private:
int variable;

public:
A()
{
std::cout << "A created!" << std::endl;
}

~A()
{
std::cout << "A destructed!" << std::endl;
}

};

class B
{
private:
size_t arrayOnHeapSize; // size of array on heap
A* arrayOnHeap; // memory must be allocated before this is used.

public:
B(size_t arrSize) :
arrayOnHeapSize(arrSize)
{
arrayOnHeap = new A[arrSize]; // must deallocate memory manually, use "delete[]" arrays of objects
std::cout<< "B created with size" << arrSize << '!' << std::endl;
}

~B()
{
delete[] arrayOnHeap; // must deallocate memory manually
std::cout << "B destructed! Wouldn't have had to do memory management manually if I had used a vector!" << std::endl;
}

B(const B&) = delete; // If you need to make a copy, you'll have to make a copy constructor that performs a deep copy or adds some (ugly) reference counting logic. Could also opt to implement a move constructor. If you copied this as is, the pointer will get copied, one B will get destructed freeing the memory, then the other B will have a dangling pointer and try to free that upon destruction. No good.

};

int main()
{
B* arrayOfB[3];
arrayOfB[0] = new B(2);
arrayOfB[0] = new B(5);
arrayOfB[0] = new B(7);
delete arrayOfB[0]; // must deallocate manually, using "delete" instead of "delete[]" because these are each 1 object, not arrays.
delete arrayOfB[1];
delete arrayOfB[2];
// Don't need to delete arrayOfB as it is a local on the stack and will be taken care of as the function exits.
}

关于c++ - 在 C++ 中创建另一个类的多个类对象成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40916000/

24 4 0
文章推荐: javascript - 如何获取特色图像并将其图像路径放入内联样式中,即。
?
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com