Ove*_*ker 5 c++ constructor operator-overloading
为什么在运算符重载时返回允许的构造函数?
这是一个例子:
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 );
}
Run Code Online (Sandbox Code Playgroud)
它似乎是返回对象的构造函数而不是对象本身?什么回到那里?
这似乎更有意义:
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;
}
Run Code Online (Sandbox Code Playgroud)
M.M*_*M.M 10
在C++中,语法:Typename(arguments)表示创建Typename 1类型的未命名对象(也称为临时对象).参数传递给该对象的构造函数(或用作基本类型的初始化器).
它与你的第二个例子非常相似:
Complex somenumber( Real, Imaginary);
return somenumber;
Run Code Online (Sandbox Code Playgroud)
唯一的区别是对象有一个名字.
两个版本之间存在一些细微差别,涉及复制或将对象移回调用函数. 更多信息在这里