问题描述
我正在尝试为某些工作创建一个库,并且正在使用运算符重载进行赋值操作.假定X和Y是该类的两个实例,因此具有=重载:
I'm trying to create a library for some work and am using operator overloading for assignment operation.Supposed X and Y are two instances of the class that has = overloaded thus:
A& A::operator=(A &rhs)
{
A::assign(*this, rhs);
return *this;
}
当我这样做时:
A z;
z = x + y; // x and y are other instances of class A
一切都很好,但是,当我做一个
everything is fine, however, when I do a `
A p = q + r;
重载的例程不会被调用.我对运算符重载的经验不是很丰富,可以解释一下发生了什么.一种解释可能是p只是已经创建的q + r对象的别名,但是z会创建类A的新实例,因此在将z分配给运算符时会重载运算符.有点像:
the overloaded routine does not get called. I'm not very experienced with operator overloading, can somebody explain whats happening. One explanation might be that p is just an alias for q + r object created already, however, z creates a new instance of class A and hence operator overloading kicks in when z is assigned to. Sort of like:
#include <iostream>
using namespace std;
class X
{
public:
X();
};
X::X()
{
cout<<"called"<<endl;
}
int main(int argc, char *argv[])
{
X e; X f;
X g = e;
}
其中被调用仅被打印两次,对于e和f分别打印一次,而对于g不打印.
where called gets printed only twice, once each for e and f, and does not get printed for g.
如果是这样,有人可以建议一种方法来触发p的运算符重载.
If that's the case, can somebody suggest a way to trigger operator overloading for p.
谢谢.
推荐答案
如果您声明变量并在同一行上对其进行初始化,它仍将调用复制构造函数.
If you declare a variable and initialize it on the same line, it will still call the copy constructor.
有两种初始化语法:
X a;
X b(a);
X a;
X b = a;
它们的含义略有不同,但是在大多数情况下,它们的作用相同.不同之处在于是否保证编译器可以避免某些构造/破坏.无论哪种情况,都将调用复制构造函数,因为您正在构造一个对象.我不太记得关于担保差异的细节.
There are slight differences as to what they mean, but in most cases they do the same. The difference is whether or not the compiler is guaranteed to avoid certain constructions/destructions. In either case, the copy constructor will be called, because your are constructing an object. I can't quite remember what the details are as for the difference in guarantees.
这篇关于赋值运算符重载已跳过/未发生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!