怎么解决构造函数和类型转换运算符歧义的有关问题
如何解决构造函数和类型转换运算符歧义的问题?
错误:
Compiling the source code....
$g++ -std=c++11 main.cpp -o demo -lm -pthread -lgmpxx -lreadline 2>&1
main.cpp: In function 'int main()':
main.cpp:41:14: error: ambiguous overload for 'operator+' in 't0 + 1'
main.cpp:41:14: note: candidates are:
main.cpp:41:14: note: operator+(int, int)
main.cpp:20:6: note: Test Test::operator+(Test)
这个能解决么?是我什么地方搞错了么?
#include <iostream>这个程序是有问题的。
using namespace std;
class Test
{
public:
Test ( int n );
Test operator+( Test t );
operator int();
int m_n;
};
Test::Test( int n )
{
cout << "Test(int) get" << n << endl;
m_n = n;
}
Test Test::operator+( Test t )
{
t.m_n += m_n;
return t;
}
Test::operator int()
{
cout << "operator int() from" << m_n << endl;
return m_n;
}
ostream& operator<<( ostream& os, Test t )
{
cout << t.m_n;
}
int main()
{
Test t0( 1 );
int s = 0;
s = t0 + 1;
cout << s << endl;
return 0;
}
错误:
Compiling the source code....
$g++ -std=c++11 main.cpp -o demo -lm -pthread -lgmpxx -lreadline 2>&1
main.cpp: In function 'int main()':
main.cpp:41:14: error: ambiguous overload for 'operator+' in 't0 + 1'
main.cpp:41:14: note: candidates are:
main.cpp:41:14: note: operator+(int, int)
main.cpp:20:6: note: Test Test::operator+(Test)
这个能解决么?是我什么地方搞错了么?
#include <iostream>
using namespace std;
class Test
{
public:
explicit Test( int n );
Test operator+( Test t );
operator int();
int m_n;
};
Test::Test( int n )
{
cout << "Test(int) get " << n << endl;
m_n = n;