gpt4 book ai didi

c++ - 重载运算符 >> 像 std::cout

转载 作者:行者123 更新时间:2023-11-30 02:03:41 27 4
gpt4 key购买 nike

我想创建一个类似于 std::cout 的类。我知道如何重载 >> 和 << 运算符,但我想重载 << 运算符,使其成为输入,就像在 std::cout 中一样。

应该是这样的:

class MyClass
{
std::string mybuff;
public:
//friend std::???? operator<<(????????, MyClass& myclass)
{
}
}
.
.
.

MyClass class;
class << "this should be stored in my class" << "concatenated with this" << 2 << "(too)";

谢谢

最佳答案

class MyClass
{
   std::string mybuff;
 public:
//replace Whatever with what you need
MyClass& operator << (const Whatever& whatever)
{
//logic
return *this;
}

//example:
MyClass& operator << (const char* whatever)
{
//logic
return *this;
}
MyClass& operator << (int whatever)
{
//logic
return *this;
}
};

关于c++ - 重载运算符 >> 像 std::cout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11516932/

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