[英]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文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.