【发布时间】:2017-10-29 22:45:00
【问题描述】:
我有一个程序的代码可以完美运行,但编译器仍然会输出这个烦人的警告:
warning: ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second:
我的程序的简化版本是:
#include <iostream>
#include <iomanip>
class point
{
public:
point( int x = 0, int y = 0 )
: _x( x ), _y( y )
{}
point( const point &p )
: _x( p._x ), _y( p._y )
{}
int & x( ) { return _x; }
int & y( ) { return _y; }
private:
int _x, _y;
};
class matrix
{
public:
int operator()( int x, int y ) const
{ return _array[ index( x, y ) ]; }
int operator()( point< int > p ) const
{ return operator()( p.x( ), p.y( ) ); }
int operator()( int x, int y, int value )
{
_array[ index( x, y ) ] = value;
return _array[ index( x, y ) ];
}
int operator()( point< int > p, int value )
{ return operator()( p.x( ), p.y( ), value ); }
private:
int _array[ 4 * 5 ];
int index( int x, int y ) const
{ return y * Width + x; }
};
int main( )
{
std::cout << "Filling matrix." << std::endl;
matrix< int, 4, 5 > m;
for ( int y = 0; y < 5; ++y )
for ( int x = 0; x < 4; ++x )
{
m( x, y, ( y * 4 + x ) );
}
std::cout << "Reading matrix." << std::endl;
for ( int y = 0; y < 5; ++y )
{
std::cout << std::endl << "|";
for ( int x = 0; x < 4; ++x )
{
std::cout << std::setw( 3 ) << std::setfill( ' ' ) << m( x, y ) << " |";
}
}
std::cout << std::endl << "Done." << std::endl;
}
我看不出我的operator() 重载有什么问题。
有什么想法吗?
【问题讨论】:
标签: c++ operator-overloading default-value overloading