c++中类型转换运算符重载问题

#include <iostream>

using namespace std;
class A{
private:
    int a;
    string str = "hello";
public:
    A(int a):a(a){}
    A &operator =(A &i){
        cout << "赋值运算被调用了" << endl;
        this->a = i.a;
        return *this;
    }
    int get_a(){
        return a;
    }
    operator int(){
        return a;
    }
    operator string(){
        cout << "casdcasdcasd" << endl;
        return str;
    }
};
int main()
{
    A i(2);
    int a = i;
    cout << a << endl;
    string str;
    str = i;
    cout << str << endl;

    return 0;
}

问题描述:当我做类型强转时会造成二义性的问题

对上述代码中str = i;会报错

D:\c++code\day3\main.cpp:77: error: ambiguous overload for 'operator=' (operand types are 'std::string {aka std::basic_string<char>}' and 'A')
     str = i;
         ^

原因是因为编译器在编译时候看到了int类型转换和string类型转换,对于编译器来说,string是一个自定义的类,它并不知道用户是想i转为int还是string ,解决的方法有加强转表明类型,或者说注释掉int或者string的类型转换或者在初始化时使用;

#include <iostream>

using namespace std;
class A{
private:
    int a;
    string str = "hello";
public:
    A(int a):a(a){}
    A &operator =(A &i){
        cout << "赋值运算被调用了" << endl;
        this->a = i.a;
        return *this;
    }
    int get_a(){
        return a;
    }
    operator int(){
        return a;
    }
    operator string(){
        cout << "casdcasdcasd" << endl;
        return str;
    }
};
int main()
{
    A i(2);
    int a = i;
    cout << a << endl;
    string str;
    str = (string)i;
    cout << str << endl;

    return 0;
}

或者

#include <iostream>

using namespace std;
class A{
private:
    int a;
    string str = "hello";
public:
    A(int a):a(a){}
    A &operator =(A &i){
        cout << "赋值运算被调用了" << endl;
        this->a = i.a;
        return *this;
    }
    int get_a(){
        return a;
    }
//    operator int(){
//        return a;
//    }
    operator string(){
        cout << "casdcasdcasd" << endl;
        return str;
    }
};
int main()
{
 A i(2);
 string str;
    str = (string)i;
    cout << str << endl;

    return 0;
}

初始化时使用

#include <iostream>

using namespace std;

class A{
private:
    int a;
    string str = "hello";
public:
    A(int a):a(a){}
    A &operator =(A &i){
        cout << "赋值运算被调用了" << endl;
        this->a = i.a;
        return *this;
    }
    int get_a(){
        return a;
    }
    operator int(){
        return a;
    }
    operator string(){
        cout << "casdcasdcasd" << endl;
        return str;
    }
};
int main()
{
    A i(2);
//    int a = i;
//    cout << a << endl;
    string str = i;
    //str = (string)i;
    cout << str << endl;

    return 0;
}

这些解决办法都是为了告诉编译器,我要转什么类型。

并非本人解答,问的老师。

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值