默认构造函数和对象复制
我想知道为什么在这种情况下需要声明默认构造函数。一方面,如果我省略它,编译器不会自动执行此操作吗?不管怎样,我仍然不明白为什么有必要。另外,即使我省略 'obj_B = origin.obj_B;',我也会收到错误
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;}; //error:no matching function for call
//to B::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'm wondering why I need to declare a default constructor in this case. For one thing doesn't the compiler do that automatically if i leave it out? And regardless, I still don't see why its necessary. Also, I get the error even if I omit 'obj_B = origin.obj_B;'
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;}; //error:no matching function for call
//to B::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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您不指定备用构造函数,编译器只会创建默认构造函数。
因为您做了:
不会为您创建默认构造函数。
您收到的具体错误是因为 A(A const &origin) 没有明确指定用于 obj_B 的构造函数。
下面的代码可以工作:
顺便说一下,函数定义上不需要尾随分号。
The compiler only creates a default constructor if you don't specify an alternate constructor.
Because you made:
The default constructor will not be created for you.
The specific error you're getting is because A(A const &origin) doesn't specify the constructor to use for obj_B explicitly.
The following code would work:
By the way, you don't need a trailing semicolon on a function definition.
如果您没有为类定义任何 构造函数,编译器将合成一个默认构造函数。如果您定义了另一个构造函数(例如,带有参数的构造函数),那么编译器不会为您合成一个构造函数,您必须自己定义一个构造函数。
如果您关心的话,C++ 0x 添加了一个“=default;”声明告诉编译器提供默认情况下提供的 ctor,即使您已经定义了另一个 ctor。
If you don't define any ctors for a class, the compiler will synthesize a default constructor. If you define another constructor though (e.g., one that takes an argument) then the compiler does not synthesize one for you, and you have to define one yourself.
In case you care, C++ 0x adds an "=default;" declaration to tell the compiler to provide a ctor that it would have provided by default, even if you have defined another ctor.
要为
A
定义一个不需要B
默认构造函数的复制构造函数,请使用成员初始值设定项语法:To define a copy constructor for
A
that does not require a default constructor forB
, use member initializer syntax:最后一点...
假设您没有定义非默认构造函数,则未能定义默认构造函数将导致 theArray[] 的元素未定义。这是一个坏习惯,通常会导致以后出现错误。
To make one final point...
Assuming you hadn't defined a non-default constructor, failing to define a default constructor would've resulted in the elements of theArray[] being undefined. That is a bad habit to get into usually leading to bugs down the road.