复制对象时,静态声明数组的问题,即被复制对象的成员对象的成员
我有一个 A 对象的向量。类 A 包含类型 B 的成员对象。类 B 包含静态声明的 bool 数组。当我将 A 对象复制到向量中时,布尔数组中的值会丢失。我认为这不应该成为问题,因为 bool 数组是静态声明的。我需要使用复制构造函数来处理这个问题吗?
class B
{
public:
bool theArray[5] ;
B(bool x) {theArray[1] = x;};
B(){};
};
class A
{
public:
B obj_B;
A() : obj_B(1) {};
A(A const &origin) : obj_B(origin.obj_B){};
};
int main ()
{
std::vector <A> someAs;
for(int q=0;q<10;q++)
someAs.push_back(A());
for(int q=0;q<10;q++)
std::cout << someAs[q].obj_B.theArray[1] << std::endl;
}
I have a vector of A objects. class A contains a member object of type B. class B contains a statically declared array of bool. When I copy an A object into the vector, the values in the bool array are lost. I though this shouldn't be a problem because the array of bool is statically declared. Do I need to handle this using a copy constructor?
class B
{
public:
bool theArray[5] ;
B(bool x) {theArray[1] = x;};
B(){};
};
class A
{
public:
B obj_B;
A() : obj_B(1) {};
A(A const &origin) : obj_B(origin.obj_B){};
};
int main ()
{
std::vector <A> someAs;
for(int q=0;q<10;q++)
someAs.push_back(A());
for(int q=0;q<10;q++)
std::cout << someAs[q].obj_B.theArray[1] << std::endl;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不需要定义复制构造函数来执行此操作。我不确定“静态数组”是什么意思,因为有两种含义,但都不需要复制构造函数。
如果您的意思是“静态大小的数组”,如下所示:
那么默认的复制构造函数将对要复制的对象中的元素进行成员复制。
如果您的意思是“静态布尔数组”,如下所示:
那么复制构造函数不会触及该数组,因为它在类的所有实例之间共享。
如果您的 bool 数组被损坏,您可能会遇到内存损坏错误,可能是因为读取了数组的末尾或取消引用了错误的指针。我会研究这个,因为默认的复制行为确实会给你你想要的。
You shouldn't need to define a copy constructor to do this. I'm not sure what you mean by "static arrays," since there are two meanings, but neither require a copy constructor.
If you mean "array that's statically sized," like this:
Then the default copy constructor will do a memberwise copy of the elements from the object being copied.
If you mean "a static array of bools," like this:
Then the copy constructor won't touch this array because it's shared across all instances of the class.
If your array of
bool
s is getting corrupted, you might have a memory corruption bug on your hands, perhaps by reading off the end of an array or dereferencing a bad pointer. I'd look into this, since the default copy behavior will indeed give you what you want.