今天编写了下列代码(仅仅显示关键代码片段),在VS2015上运行正常,但是在VC6.0下出现错误提示。
#include<iostream>
using namespace std;
class vct
{
private:
double x, y;
public:
//vct(double X = 0, double Y = 0) { x = X, y = Y; }
//~vct() {}
//void set(double X = 0, double Y = 0) { x = X, y = Y; }
//vct operator+(vct& rival);
//vct operator-(vct& rival);
friend ostream& operator<<(ostream& out, const vct& rival);
};
ostream& operator<<(ostream& out, const vct& rival)
{
out << "The Vector is (" << rival.x << ',' << rival.y << ")" << endl;return out;
}
此处重载了用于输出流对象cout的提取运算符'<<',但是在VC6.0下提示:
error C2593: 'operator <<' is ambiguous
并且出现了无法访问私有成员变量的问题,尽管已经定义了友元函数:
error C2248: 'x' : cannot access private member declared in class 'vct'
error C2248: 'y' : cannot access private member declared in class 'vct'
解决办法是,在类定义之前首先声明类,并且将友元函数的函数头放置在前面,因为友元函数不是成员函数,这么做是合理的:
#include<iostream>
using namespace std;
class vct; //此处声明类
ostream& operator<<(ostream& out,const vct& rival); //此处声明函数头
class vct
{
private:
double x,y;
public:
//vct(double X = 0, double Y = 0) { x = X, y = Y; }
//~vct() {}
//void set(double X = 0, double Y = 0) { x = X, y = Y; }
//vct operator+(vct& rival);
//vct operator-(vct& rival);
friend ostream& operator<<(ostream& out,const vct& rival);//再次声明
};
ostream& operator<<(ostream& out,const vct& rival) //友元重载函数定义
{
out<<"The Vector is ("<<rival.x<<','<<rival.y<<")"<<endl;
return out;
}