c++ multiple definitions of operator<<

前端 未结 2 533
执笔经年
执笔经年 2020-12-08 06:50

I am attempting to override the << operator for a class. The purpose is basically to implement a toString() like behavior for my class, so t

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-08 07:20

    You are putting the definition of a function in a .h file, which means that it will appear in every translation unit, violating the One Definition Rule (=> you defined operator<< in every object module, so the linker doesn't know which is "the right one").

    You can either:

    • write just the declaration of your operator (i.e. its prototype) in the .h file and move its definition to rectangle.cpp
    • make operator<< inline - inline functions are allowed to be defined more than once, as long as all the definitions are identical.

    (Also, you should use header guards in your includes.)

提交回复
热议问题