#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;
}
这些解决办法都是为了告诉编译器,我要转什么类型。
并非本人解答,问的老师。