gpt4 book ai didi

C++ 重载运算符 << 让我做噩梦

转载 作者:行者123 更新时间:2023-11-28 00:35:19 25 4
gpt4 key购买 nike

我查看了与我的问题相关的所有其他线程,例如:

Overloading the << operator

operator << overload

我觉得我很接近解决我的问题,但没有成功。我希望你们能提供帮助。

我有下面的示例代码,我需要让他编译:

auto fan3 = std::make_shared<Fan>(3,"Not Connected");

//.... lots of code

std::cout << "User: " << *fan3 << " not connected" << std::endl;

我收到错误“二进制表达式的无效操作数('basic_ostream >' 和'mtm::Fan')”,所以我认为我需要实现 << 运算符。

我尝试将以下内容放入 fan.h 中:

friend std::ostream& operator<<(std::ostream& os, Fan& fan);

但我收到“ undefined symbol ”。将它放在类之外(当然没有“ friend ”)会导致同样的错误。

我想我对这种行为有些不太了解 - 我确实实现了其他运算符重载,但 << 到目前为止只是给我带来了麻烦。

请向我解释我缺少什么以及如何解决这个问题。感谢您的宝贵时间!

最佳答案

您需要像这样声明一个自由函数:

std::ostream& operator<<(std::ostream& os, const Fan& fan);

然后像这样实现它:

std::ostream& operator<<(std::ostream& os, const Fan& fan)
{
return os << fan.whatever;
}

如果您的类在命名空间中而不是在类本身中,则应在您的类的命名空间中完成此操作。

关于C++ 重载运算符 << 让我做噩梦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21160145/

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