这是我编写的一些简单代码。它只是复制一个对象,并使用重载的运算符显示其数据功能。
//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;
}
Run Code Online (Sandbox Code Playgroud)
成员函数在.cpp文件中定义。问题是当我编译该程序时,我被告知
there are multiple definitions of operator<<(ostream& out, Sphere& fSphere)
Run Code Online (Sandbox Code Playgroud)
这很奇怪,因为outstream运算符是一个非成员函数,因此应该可以在类之外定义它。但是,当我在类中定义此运算符时,程序运行良好。这是怎么回事?
似乎您在头文件中定义了运算符,并将此头包含在多个cpp模块中。或者在另一个cpp模块中包含一个具有功能定义的cpp模块。通常,错误消息会显示在何处定义了多个函数。因此,请重新阅读错误消息的所有行
考虑到最好将运算符声明为
ostream& operator<<(ostream& out, const Sphere &fSphere);
Run Code Online (Sandbox Code Playgroud)