简体   繁体   English

在类外定义重载的下游运算符

[英]Defining an overloaded outstream operator outside a class

Here is some simple code that I wrote. 这是我编写的一些简单代码。 It simply copies an object and displays it data functions with an overloaded operator. 它只是复制一个对象,并使用重载的运算符显示其数据功能。

      //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;
    }

The member functions are defined in a .cpp file. 成员函数在.cpp文件中定义。 The problem is that when I compile this program I am told 问题是当我编译该程序时,我被告知

 there are multiple definitions of operator<<(ostream& out, Sphere& fSphere)

This is strange because the outstream operator is a non-member function so it should be able to be defined out of the class. 这很奇怪,因为outstream运算符是一个非成员函数,因此应该可以在类外定义它。 Yet the program works well when I define this operator inside the class. 但是,当我在类中定义此运算符时,程序运行良好。 Whats going on? 这是怎么回事?

It seems you defined the operator in a header file and include this header in multiple cpp modules. 似乎您在头文件中定义了运算符,并将此头包含在多个cpp模块中。 or you include one cpp module with the function definition in other cpp module. 或者在另一个cpp模块中包含一个具有功能定义的cpp模块。 Usually the error mesage shows where a function is multiple defined. 通常,错误消息会显示在何处定义了多个函数。 So reread all lines of the error message 因此,请重新阅读错误消息的所有行

Take into account that it would be better to declare the operator as 考虑到最好将运算符声明为

ostream& operator<<(ostream& out, const Sphere &fSphere);

Looks like the code you presented if the header file. 看起来像您在头文件中显示的代码。 And it contains the definition of operator<< , so any file including your header has its own copy of this definition, hence "multiple definitions" error. 并且它包含operator<<定义 ,因此任何文件(包括标题)都具有该定义的自己的副本,因此会出现“多个定义”错误。 Add the keyword inline to your function, or move the function to .cpp file. 将关键字inline添加到函数中,或将函数移至.cpp文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM