一段代码引起的思考-----编译器

2014-11-24 12:26:55 · 作者: · 浏览: 0

今天碰到一个问题,同学写了一段操作符重载的代码,但是总是编译不过,总是提醒'operator <<' is ambiguous,这是指'<<'被多次定义了,他用的是vc++ 6.0,代码如下:

#include

using namespace std;



class Point

{

public:

Point(float x=0,float y=0);

void setPoint(float,float);

float getXpoint() const {return x;}

float getypoint() const {return y;}

friend ostream & operator<< (ostream & os,Point & p);

private:

float x;

float y;

};



Point::Point(float a,float b)

{

x=a;

y=b;

}



void Point::setPoint(float a,float b)

{

x=a;

y=b;



}



ostream & operator<< (ostream & output,Point & p)

{

output << "[" <
return output;

}



int main()

{

Point p(4.5,5.5);



cout << "x=" << p.getXpoint() << ",y=" << p.getypoint() << endl;

p.setPoint(8.5,9.5);

cout << p;



return 0;
www.2cto.com
}

这是比较平常的重载‘<<’的例子,我猜想是全局命名空间造成编译不过的,于是我们把最开始的using namespace std这句话去掉,以std::cout和std::endl代替之,再次编译,通过。
我把未修改过的代码用gcc 4.4.3编译一下,也通过了,相同的代码在不同的编译器上也可能会有不同的结果。
在这里我想到了程序的可控性问题,怎样让变量和数据的传递在控制之中,让程序的通用性比较好,避免出现在这个编译器上编译通过,而在另外一个编译器上编译错误,通过这个列子,尽量不要使用全局的命名空间,而使用std::cout和std:endl等代替。


摘自 maochencw的专栏