【发布时间】:2014-09-01 23:43:27
【问题描述】:
为什么在运算符重载中允许返回构造函数?
这是一个例子:
Complex Complex::operator*( const Complex &operand2 ) const
{
double Real = (real * operand2.real)-(imaginary * operand2.imaginary);
double Imaginary = ( real * operand2.imaginary)+(imaginary * operand2.real);
return Complex ( Real, Imaginary );
}
似乎返回的是对象的构造函数,而不是对象本身?它在那里返回什么?
这似乎更有意义:
Complex Complex::operator*( const Complex &operand2 ) const
{
double Real = (real * operand2.real)-(imaginary * operand2.imaginary);
double Imaginary = ( real * operand2.imaginary)+(imaginary * operand2.real);
Complex somenumber ( Real, Imaginary );
return somenumber;
}
【问题讨论】:
-
Complex(...)是Complex的instance 的构造。构造函数用于初始化该类型的对象,在本例中为临时对象。 -
“返回构造函数”???到底是什么让你断定它是“返回构造函数”?在 C++ 语言中,构造函数的名称类似于
Complex::Complex。注意 - 两个相同的部分由::分隔。那将是一个构造函数名称。现在,在您发布的代码中,您在哪里看到任何看起来像构造函数的东西? -
为什么不
return {Real, Imaginary};? -
我以前从未见过这种语法。语法是否与马特在下面的回答相同?
标签: c++ constructor operator-overloading