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

C++如何重载运算符?Hackerrank Box-It挑战<和<<运算符重载问题

C++ 运算符重载解决方案(针对Hackerrank Box-It 挑战)

核心问题说明

  • 你当前的代码错误地将<<运算符重载为了两个Box对象维度相加的逻辑,完全不符合该挑战要求的<<运算符(流输出功能)的语义
  • 缺少<运算符的重载实现

正确重载实现

1. 小于运算符<重载

<运算符用于按规则比较两个Box的大小,规则为:优先比较长度,长度相等则比较宽度,宽度相等则比较高度,符合要求则返回true,否则返回false。该运算符可直接作为类的成员函数实现:

bool operator<(const Box& other) const {
    if (l < other.l) return true;
    if (l == other.l && b < other.b) return true;
    if (l == other.l && b == other.b && h < other.h) return true;
    return false;
}

2. 流输出运算符<<重载

<<运算符用于将Box的三个维度输出到流中,该运算符第一个参数必须是输出流对象,因此不能作为类成员函数实现,需要声明为类的友元全局函数:
首先在Box结构体内部添加友元声明:

friend ostream& operator<<(ostream& os, const Box& box);

然后在类外部实现该函数:

ostream& operator<<(ostream& os, const Box& box) {
    os << box.l << " " << box.b << " " << box.h;
    return os;
}

修改后完整可运行代码

#include <iostream>
using namespace std;

struct Box
{
    public:
        int l,b,h;    
        
        int getLength(void);
        int getBreadth(void);
        int getHeight(void);        
        
        long long CalculateVolume(void) ;
        
        // 重载<运算符
        bool operator<(const Box& other) const {
            if (l < other.l) return true;
            if (l == other.l && b < other.b) return true;
            if (l == other.l && b == other.b && h < other.h) return true;
            return false;
        }
        
        // 声明<<运算符为友元
        friend ostream& operator<<(ostream& os, const Box& box);
};

// 实现<<运算符
ostream& operator<<(ostream& os, const Box& box) {
    os << box.l << " " << box.b << " " << box.h;
    return os;
}

int Box::getLength(void) 
{
    return l;
}

int Box::getBreadth(void)
{
    return b;
}

int Box::getHeight() 
{
    return h;
}

// 修复int相乘溢出问题,先将其中一个值转为long long再运算
long long Box::CalculateVolume(void) 
{
    return (long long)l * b * h;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 17:27:00