如何解决构造函数和类型转换运算符歧义的问题?
本帖最后由 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;
}
#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;
}
#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;
}