[英]Why will C++ copy constructor fail?
#include <iostream>
#include <string>
using namespace std;
class A
{
public:
A() { i=1; j=2;};
A (A &obj) { i= obj.i+100; j= obj.j+100;};
int i;
int j;
};
class B:public A
{
public:
B():A() {i=10; j=20; k=30;};
B(A &obj) { A::A(obj); k=10000; };//
int k;
};
int main()
{
A dog;
B mouse(dog);
cout<<mouse.i<<endl;
cout<<mouse.k<<endl;
return 0;
}
I try to write a copy constructor for the derived class that takes advantage of the copy constructor for the base class. 我尝试为派生类编写一个复制构造函数,以利用基类的复制构造函数。 I expect that
mouse.i
should be 101, but in fact the compiling result is 1. The value for mouse.k
is 10000, which is expected. 我希望
mouse.i
应该为101,但实际上编译结果为mouse.k
值为10000,这是预期的。 I was wondering what's wrong with my code. 我想知道我的代码有什么问题。
You must use the initialization list to call the parent's constructor (and you should do it for all other members also): 您必须使用初始化列表来调用父级的构造函数(并且还应该对所有其他成员执行此操作):
B(A const& obj) : A(obj), k(10000) {}
Additionally, when copying you do not modify the original object, so you should take a const
reference to it. 另外,在复制时,您不会修改原始对象,因此您应该对其进行
const
引用。 That will allow you to copy from constant objects (or through constant references), improving const-correctness. 这将允许您从常量对象(或通过常量引用)进行复制,从而提高const正确性。
In this constructor: 在此构造函数中:
B(A &obj) { A::A(obj); k=10000; };
A::A(obj);
does not initialise the base sub-object; 不初始化基础子对象; instead, it creates a local object also called
obj
. 而是创建一个本地对象,也称为
obj
。 It's equivalent to A::A obj;
等效于
A::A obj;
, which is equivalant to A obj;
,相当于
A obj;
. 。 [UPDATE: or possibly it does something else, or possibly it's ill-formed - in any event, it's wrong.]
[更新:或者可能做其他事情,或者格式不正确-无论如何,这是错误的。]
You want to use an initialiser list: 您要使用初始化程序列表:
B(A & obj) : A(obj), k(10000) {}
Also, you almost certainly want the constructor parameters to be A const &
, to allow construction from constant objects or temporaries. 另外,您几乎可以肯定希望构造函数的参数为
A const &
,以允许从常量对象或临时对象进行构造。
You should initialize the base class like this: 您应该像这样初始化基类:
B(A &obj):A(obj) { k=10000; }
(more on this at What are the rules for calling the superclass constructor? ). (有关更多信息,请参见调用超类构造函数的规则是什么? )。 And a side-note: use
const
for copy constructor arguments: 还有一个注释:使用
const
作为复制构造函数参数:
A (const A &obj) {...}
EDIT : 编辑 :
The preferred way to initialize instance members is through an initialization list, so your ctor will look like 初始化实例成员的首选方法是通过初始化列表,因此您的ctor看起来像
B(A &obj):A(obj), k(10000) { }
#include <iostream>
#include <string>
using namespace std;
class A
{
public:
A()
{
i=1;
j=2;
}
A (A &obj)
{
i= obj.i+100;
j= obj.j+100;
}
int i;
int j;
};
class B:public A
{
public:
B():A() {i=10; j=20; k=30;}
B(A &obj)
:A(obj)
{
//A::A(obj);
k=10000;
}//
int k;
};
int main()
{
A dog;
B mouse(dog);
cout<<mouse.i<<endl;
cout<<mouse.k<<endl;
return 0;
}
This work for me 这对我有用
B(A &obj)
{
A::A(obj)
}
Is illegal on gcc compiler 在gcc编译器上是非法的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.