在类外部定义重载流出操作符
Defining an overloaded outstream operator outside a class
这是我写的一些简单的代码。它只是复制一个对象,并通过重载操作符显示其数据函数。
//Base
#include<iostream>
#include<istream>
#include<ostream>
using std::ostream;
using std::istream;
using namespace std;
class Sphere{
public:
Sphere(double Rad = 0.00, double Pi = 3.141592);
~Sphere();
Sphere(const Sphere& cSphere)
//overloaded output operator
friend ostream& operator<<(ostream& out, Sphere &fSphere);
//member function prototypes
double Volume();
double SurfaceArea();
double Circumference();
protected:
double dRad;
double dPi;
};
//defining the overloaded ostream operator
ostream& operator<<(ostream& out, Sphere& fSphere){
out << "Volume: " << fSphere.Volume() << 'n'
<< "Surface Area: " << fSphere.SurfaceArea() << 'n'
<< "Circumference: " << fSphere.Circumference() << endl;
return out;
}
成员函数在.cpp文件中定义。问题是,当我编译这个程序时,我被告知
there are multiple definitions of operator<<(ostream& out, Sphere& fSphere)
这很奇怪,因为outstream操作符是非成员函数,所以它应该能够在类外定义。然而,当我在类中定义这个操作符时,程序运行良好。发生什么事了?
似乎您在头文件中定义了操作符,并将此头包含在多个cpp模块中。或者在另一个CPP模块中包含一个CPP模块和函数定义。通常,错误消息会显示函数是多重定义的。所以重读错误信息
的所有行考虑到最好将操作符声明为
ostream& operator<<(ostream& out, const Sphere &fSphere);
看起来像您在头文件中提供的代码。并且它包含operator<<
的定义,因此包括头文件在内的任何文件都有该定义的自己的副本,因此出现"多个定义"错误。将关键字inline
添加到函数中,或者将函数移动到.cpp文件中。