[英]c++ untyped value object/variable library with defined operation overloads
[英]Does C++ automatically commute some operation overloads?
我一直在尝试理解操作重载以及类和基本类型之间的交换属性。 我声明了 Test to Int 星号操作,但没有声明 Int to Test,只是为了看看 C++ 是否会自动提供某种可交换的 function。 测试代码为:
#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 << std::endl;
std::cout << "Second result: " << (3 * my_test).x << std::endl;
return 0;
}
与 output:
第一个结果:警报! 对 Int 的测试发生了! 2
第二个结果:警报! 测试测试发生了! 3
第一个结果与预期的一样,但对于第二个结果,我预计会出现错误或一些我不知道的 function 来完成这项工作。 相反,使用了测试到测试操作......有人可以解释为什么以及发生了什么吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.