小编gza*_*pis的帖子

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 << …
Run Code Online (Sandbox Code Playgroud)

c++ operator-overloading

3
推荐指数
1
解决办法
84
查看次数

标签 统计

c++ ×1

operator-overloading ×1