god2019 2021-12-14 17:17 采纳率: 80%
浏览 17
已结题

运行代码的时候出现LNK2005错误operator==()已经在其中一个被定义

#ifndef POSTYPE_H
#define POSTYPE_H
struct PosType
{
    int row, col;
};
PosType operator+(const PosType p1, const PosType p2) {
    PosType p;
    p.row = p1.row + p2.row;
    p.col = p1.col + p2.col;
    return p;
}
bool operator== (const PosType p1, const PosType p2) {
    return p1.row == p2.row && p1.col == p2.col;
}
#endif

出问题的代码在这个头文件中定义,因为要使用所以在另一个头文件MAZE.H中包含了该头文件,
运行程序的时候,在main中包含了MAZE.H的头文件,运行后提示错误:
LNK2005 "bool __cdecl operator==(struct PosType,struct PosType)" (??8@YA_NUPosType@@0@Z) 已经在 Maze.obj 中定义 Stageone F:\workspace\Stageone\源.obj
LNK2005 "struct PosType __cdecl operator+(struct PosType,struct PosType)" (??H@YA?AUPosType@@U0@0@Z) 已经在 Maze.obj 中定义 Stageone F:\workspace\Stageone\源.obj

请大大们帮忙看看要怎么修改?

  • 写回答

2条回答 默认 最新

  • 关注

    运算符的重载要么作为类的成员方法,要么做成友元函数。你这里既不是成员方法,也不是友元函数。
    代码修改如下:

    #ifndef POSTYPE_H
    #define POSTYPE_H
    struct PosType
    {
        int row, col;
    
        PosType operator+(const PosType p1, const PosType p2) {
            PosType p;
            p.row = p1.row + p2.row;
            p.col = p1.col + p2.col;
            return p;
        }
        bool operator== (const PosType p1, const PosType p2) {
            return p1.row == p2.row && p1.col == p2.col;
        }
    };
    
    #endif
    
    

    或者:

    #ifndef POSTYPE_H
    #define POSTYPE_H
    struct PosType
    {
        int row, col;
    
        PosType operator+(const PosType p1, const PosType p2) {
            PosType p;
            p.row = p1.row + p2.row;
            p.col = p1.col + p2.col;
            return p;
        }
        bool operator== (const PosType p1) {
            return p1.row ==row && p1.col == col;
        }
    };
    
    #endif
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 12月22日
  • 已采纳回答 12月14日
  • 创建了问题 12月14日

悬赏问题

  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!