gpt4 book ai didi

c++ - 简单的 C++ 运算符重载帮助

转载 作者:行者123 更新时间:2023-11-30 00:58:28 26 4
gpt4 key购买 nike

如何重载 <<运算符(operator)?从我得到的错误来看,似乎是 std::cout不知道如何使用 << .

这是在一个类中:

// uint64_t UPPER, LOWER;
std::ostream & operator<<(std::ostream & stream){
if (UPPER)
stream << UPPER;
stream << LOWER;
return stream;
}

我得到 error: no match for 'operator<<' in 'std::cout << test'这似乎没有意义。

编辑:

这都不是:

std::ostream & operator<<(std::ostream & stream, uint128_t const & val){
if (val.upper())
stream << val.upper();
stream << val.lower();
return stream;
}

也不是这个:

std::ostream & operator<<(std::ostream & stream, uint128_t val){
if (val.upper())
stream << val.upper();
stream << val.lower();
return stream;
}

正在改错。

最佳答案

<<运算符有两个参数,左侧和右侧。因此,您必须使用两个参数定义函数:

std::ostream operator<<(std::ostream &os, const MyClass &obj);

据我所知,你必须在你的类定义之外定义它。在类定义内部,您只能拥有将该类作为左侧的运算符。

关于c++ - 简单的 C++ 运算符重载帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6106017/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com