简体   繁体   中英

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. 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. 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. or you include one cpp module with the function definition in other cpp module. 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. Add the keyword inline to your function, or move the function to .cpp file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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