C++会自动转换一些操作重载吗?
我一直在尝试理解操作重载以及类和基本类型之间的交换属性。我声明了 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 << std::endl;
std::cout << "Second result: " << (3 * my_test).x << std::endl;
return 0;
}
带输出:
第一个结果:警报!对 Int 的测试发生了!2
第二个结果:警报!测试到测试发生了!3
第一个结果符合预期,但对于第二个结果,我预计会出现错误或某些未知的功能来完成这项工作。相反,使用了测试到测试操作......有人可以解释为什么发生了什么吗?
回答
您的构造函数的形式为
Test(float number){
x = number;
}
就是所谓的转换构造函数。由于它不是explicit,它允许您将floataTest隐式转换为 a 。你看到在
(3 * my_test).x
这里在标准转换序列中3转换为 a ,然后通过构造函数转换。这然后允许使用。floatfloatTest(float number)operator*(Test a, Test b)
为了阻止这个,你让构造函数explicit像
explicit Test(float number){
x = number;
}