且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

c ++的多个定义operator<

更新时间:2023-11-12 22:26:58

strong>一个定义规则。快速修复是:

  inline ostream&运算符<<(ostream& out,const CRectangle& r){
return out< Rectangle:<< r.x<< ,< r.y;
}

其他是:




  • 在头文件中声明操作符,并将实现移动到 Rectangle.cpp 文件。

  • 在类定义中定义运算符。



  class CRectangle {
private:
int x,y;
public:
void set_values(int,int);
int area();
friend ostream&运算符<<(ostream& out,const CRectangle& r){
return out< Rectangle:<< r.x<< ,< r.y;
}
};

奖金:




  • 使用包含守卫

  • 使用标题中的命名空间std; 删除


    • I am attempting to override the << operator for a class. The purpose is basically to implement a toString() like behavior for my class, so that sending it to cout will produce useful output. Using a dummy example, I have the code below. When I attempt to compile, I get the foollowing error:

$ g++ main.cpp Rectangle.cpp
/tmp/ccWs2n6V.o: In function `operator<<(std::basic_ostream<char, std::char_traits<char> >&, CRectangle const&)':
Rectangle.cpp:(.text+0x0): multiple definition of `operator<<(std::basic_ostream<char, std::char_traits<char> >&, CRectangle const&)'
/tmp/ccLU2LLE.o:main.cpp:(.text+0x0): first defined here

I can't figure out why this is happening. my code is below:

Rectangle.h:

#include <iostream>
using namespace std;

class CRectangle {
    private:
        int x, y;
        friend ostream& operator<<(ostream& out, const CRectangle& r);
    public:
        void set_values (int,int);
        int area ();
};

ostream& operator<<(ostream& out, const CRectangle& r){
    return out << "Rectangle: " << r.x << ", " << r.y;
}

Rectangle.cpp:

#include "Rectangle.h"

using namespace std;

int CRectangle::area (){
    return x*y;
}

void CRectangle::set_values (int a, int b) {
    x = a;
    y = b;
}

main.cpp:

#include <iostream>
#include "Rectangle.h"

using namespace std;

int main () {
    CRectangle rect;
    rect.set_values (3,4);
    cout << "area: " << rect.area();
    return 0;
}

You're breaking the one definition rule. A quick-fix is:

inline ostream& operator<<(ostream& out, const CRectangle& r){
    return out << "Rectangle: " << r.x << ", " << r.y;
}

Others are:

  • declaring the operator in the header file and moving the implementation to Rectangle.cpp file.
  • define the operator inside the class definition.

.

class CRectangle {
    private:
        int x, y;
    public:
        void set_values (int,int);
        int area ();
        friend ostream& operator<<(ostream& out, const CRectangle& r){
          return out << "Rectangle: " << r.x << ", " << r.y;
        }
};

Bonus:

  • use include guards
  • remove the using namespace std; from the header.