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

如何将自定义类作为原始数据类型引用传入方法?

解决方案

当然可以实现这个需求,你只需要给自定义的INT类重载一个类型转换运算符,让它能隐式转换成内部存储的std::int32_t类型的引用,这样就能直接把INT对象传给接受const std::int32_t&参数的函数。

修改后的INT类代码

#include <cstdint>

class INT 
{
public:
    INT() : _value(0) {}
    INT(const std::int32_t& value) : _value(value) {}

    // 重载const引用转换运算符,适配接受const引用的函数
    operator const std::int32_t&() const {
        return _value;
    }

    // 可选:如果需要支持传给接受非const引用的函数,添加这个版本
    operator std::int32_t&() {
        return _value;
    }

private:
    std::int32_t _value;
};

完整测试代码

#include <cstdint>

// 上面的INT类代码...

static std::int32_t sum(const std::int32_t& lhs, const std::int32_t& rhs)
{
    return lhs + rhs;
}

int main()
{
    INT a, b;
    a = 15;
    b = 20;

    // 现在可以直接传入INT对象,编译器会自动调用转换运算符
    std::int32_t result = sum(a, b); // result会是35

    return 0;
}

关键说明

  • 转换运算符的作用是告诉编译器:当需要把INT对象转换成std::int32_t&或const std::int32_t&类型时,直接返回内部的_value成员引用。
  • 如果你担心隐式转换带来的意外问题,可以给转换运算符加上explicit关键字,但这样就需要显式转换(比如sum(static_cast<const std::int32_t&>(a), b)),不符合你“无需调用方法直接传入”的需求,所以这里不推荐使用explicit。
  • 非const版本的转换运算符是可选的,只有当你需要把INT对象传给接受非const引用的函数时才需要。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 09:32:33