如何解决构造函数和类型转换运算符歧义的问题?
本帖最后由 shendaowu 于 2013-07-28 08:36:58 编辑
#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>在树上看到explicit了,但是上面的还是会出错:
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;
}
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 si = 0;
Test st( 0 );
si = t0 + 1;
cout << si << endl;
st = t0 + 1;
cout << st << 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:44:15: error: no match for 'operator=' in 'st = (t0.Test::operator int() + 1)'
main.cpp:44:15: note: candidates are:
main.cpp:5:7: note: Test& Test::operator=(const Test&)
main.cpp:5:7: note: no known conversion for argument 1 from 'int' to 'const Test&'
main.cpp:5:7: note: Test& Test::operator=(Test&&)
main.cpp:5:7: note: no known conversion for argument 1 from 'int' to '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;
}
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 si = 0;
Test st( 0 );
si = (int)t0 + 1;
cout << si << endl;
st = t0 + Test(1);//或者在写一个friend operator+(const T& t,const int& d)的重载
cout << st << endl;
return 0;
}