You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

类中重载运算符引发Linker Command Error 2编译错误求助

问题排查:Linker Command Error 2 解决方案

你的链接错误核心原因是多个成员函数仅在类内声明,未提供具体实现,链接器无法找到这些函数的定义,导致链接阶段失败。

缺失实现的函数清单

  • 带参构造函数 Rectangle(int l, int w)
  • int get_length() const
  • int get_width() const
  • int get_area() const

修复步骤

在Rectangle.cpp中补充这些函数的实现,同时可以优化运算符重载的写法(改用const引用参数避免不必要拷贝、简化返回逻辑):

#include "Rectangle.h"

// 补充带参构造函数实现
Rectangle::Rectangle(int l, int w) : length(l), width(w) {}

// 补充getter函数实现
int Rectangle::get_length() const {
    return length;
}

int Rectangle::get_width() const {
    return width;
}

int Rectangle::get_area() const {
    return length * width;
}

// 优化后的运算符重载
bool Rectangle::operator <(const Rectangle& rhs) const {
    return (length * width) < (rhs.length * rhs.width);
}

bool Rectangle::operator >(const Rectangle& rhs) const {
    return (length * width) > (rhs.length * rhs.width);
}

bool Rectangle::operator !=(const Rectangle& rhs) const {
    return !(length == rhs.length && width == rhs.width);
}

bool Rectangle::operator ==(const Rectangle& rhs) const {
    return length == rhs.length && width == rhs.width;
}

额外说明

  1. 将运算符参数改为const Rectangle& rhs,既避免拷贝对象的性能损耗,也保证不会修改传入的对象;给成员函数加const修饰符,符合const正确性原则,表明函数不会修改类成员变量。
  2. 运算符返回逻辑可直接返回布尔表达式,无需冗余的if-else判断,让代码更简洁。

内容的提问来源于stack exchange,提问作者Jackson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 09:45:41