我一直在尝试理解操作重载以及类和基本类型之间的交换属性。我声明了 Test to Int 星号操作而不是 Int to Test,只是为了看看 C++ 是否会自动提供某种交换函数。测试代码为:
#include <iostream>
class Test{
public:
float x;
Test(){
x = 1;
}
Test(float number){
x = number;
}
~Test(){}
};
Test operator*(Test a, int b){
std::cout << "Alert! Test to Int happened! ";
return Test(a.x * b);
}
Test operator*(Test a, Test b){
std::cout << "Alert! Test to Test happened! ";
return Test(a.x * b.x);
}
int main(){
Test my_test;
std::cout << "First result: " << (my_test * 2).x << …Run Code Online (Sandbox Code Playgroud)