谭浩强 c++ 例子12.1 运行出错

来源:百度知道 编辑:UC知道 时间:2024/06/17 09:23:20
#include<iostream>
using namespace std;

class Point
{
public:
Point( float x=0, float y=0 );
void setPoint( float, float );

float getX() const { return x; }
float getY() const { return y; }

friend ostream & operator << ( ostream &, const Point & ); //友元 << 重载流运算符
protected:
float x,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,const Point &p )
{
output<<"["<<p.x<<","<<p.y<<"]"<<endl;
return output;
}

int main()
{
Point p( 3.5f, 6.2f );
cout<<"x="<<p.getX()<<"y="<<p.getY()<<endl<<endl;

p.setPoint( 8.5f, 6.8f );
cout<<"p(new):&quo

friend ostream & operator << ( ostream &, const Point & );
ostream & operator << ( ostream &output,const Point &p )
这两句。我把const删了就报错。说有歧义。删下面一个保留上面的。不报错。
(删了两个就一样了,传参数时,编译器不知道调用哪一个,当然报错)
还有我把protected:杠掉了。(public是公用的,protected值允许友元及派生类函数调用,不允许外部函数调用)

去了解一下const的用法

vc6.0没有完全实现C++标准,不带.h的头文件 不支持把重载函数作为友元函数!
friend ostream & operator << ( ostream &, const Point & ); //友元 << 重载流运算符
就是这个问题!!

你把头文件的声明改为:
#include<iostream.h>
把 using namespace std; 去掉 就可以通过了

建议不要用vc6.0 一般版本bug特别多,最好用vs2005/vs2008 .net技术

运行没有错误,你什么编译器