复制构造函数问题
我尝试使用复制构造函数 using 语句:
X y = X();
但是复制构造函数没有被调用。我正在使用 g++ 4.1.0。我在类中设置了 X(const X&) 和 X(x&) 构造函数。
这应该可行吗?或者我正在代码中解决一些非常基本的问题?
我的课程代码是
class A
{
public:
int i;
A(int ii)
{
i = ii;
}
A(const A&)
{
i = 5;
}
A(A&)
{
i = -1;
}
A()
{
i = 5000;
}
};
当我使用它时 A a = A();
或 A a = A(100);
,它不起作用,但是当我使用它时 A a(b);< /code> 或
A a = b;
它工作正常。
我错过了什么?我看到根据 wikipedia ,它应该可以工作,但在我的情况下不起作用:(。
预先感谢您的所有回答和评论。
I tried to use copy constructor using statement:
X y = X();
But copy constructor is not being called. I am using g++ 4.1.0. I set both X(const X&) and X(x&) constructor in the class.
Is this supposed to work or I am doing some very basic problem in the code?
My code for the class is
class A
{
public:
int i;
A(int ii)
{
i = ii;
}
A(const A&)
{
i = 5;
}
A(A&)
{
i = -1;
}
A()
{
i = 5000;
}
};
When I use it usingA a = A();
or A a = A(100);
, it does not work but when i use it A a(b);
or A a = b;
it works fine.
What is the point I am missing? I saw that according to wikipedia , it should work but it's not working in my case :(.
Thanks in advance for all your answers and comments.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在某些情况下,编译器可以省略对复制构造函数的调用。从临时对象初始化对象就是其中之一。在这种情况下,临时对象只是就地构造,而不是构造临时对象然后将其复制到命名对象中。
您可以通过构造一个命名对象然后制作该对象的副本来调用复制构造函数:
The compiler is permitted to elide the call to the copy constructor in certain situations. Initializing an object from a temporary is one of them. In this case, the temporary is simply constructed in-place instead of constructing a temporary and then copying it into the named object.
You can call the copy constructor by constructing a named object then making a copy of that:
调用默认构造函数。复制构造函数是获取对要复制的实例的引用的构造函数。
复制构造函数的要点是获取另一个相同类型的对象,并复制它。其他一切都不是复制构造函数。
calls the default constructor. The copy constructor is the one that takes a reference to an instance you want copied.
The point of a copy constructor is to take another object of the same type, and make a copy of it. Everything else is not a copy constructor.
复制构造函数由语句
X x(y);
或X x = y;
调用。当您调用
X x = X();
时,将调用默认构造函数。当您调用
X x = X(100);
时,将调用带有一个参数的构造函数。这些不是复制构造函数。The copy constructor is called by the statements
X x(y);
orX x = y;
.When you call
X x = X();
, the default constructor is called.When you call
X x = X(100);
, a constructor with one parameter is called. These are not copy constructors.当您用另一个对象初始化一个对象时,将调用复制构造函数:)。在您的第一个示例中,不调用复制构造函数是完全自然的,只会调用具有合适参数列表的构造函数。
Copy constructors are called when you initialize an object with an another object:). In your first example it is totally natural that the copy ctors are not called, only constructors with the suitable parameter lists will be called.