我在做一个简单的课,使用operator<<
。它将存储两个平行的数据数组,每个数组都有一个不同的(但已知的)数据类型。这个想法是,最终的界面会是这个样子:超载运营商<<
MyInstance << "First text" << 1 << "Second text" << 2 << "Third text" << 3;
这将使阵列看起来像这样:
StringArray: | "First text" | "Second text" | "Third text" |
IntArray: | 1 | 2 | 3 |
我能应付检查输入以确保一切的逻辑相匹配,但我很困惑operator<<
的技术细节。
我检查过的教程声称将其重载为std::ostream&
返回类型的朋友函数,但是我的类与流无关。我尝试使用void
作为返回类型,但遇到编译错误。最终我最终返回了对该类的引用,但我不确定这是为什么起作用。
这里是我到目前为止的代码:
class MyClass
{
public:
MyClass& operator<<(std::string StringData)
{
std::cout << "In string operator<< with " << StringData << "." << std::endl;
return *this; // Why am I returning a reference to the class...?
}
MyClass& operator<<(int IntData)
{
std::cout << "In int operator<< with " << IntData << "." << std::endl;
return *this;
}
};
int main()
{
MyClass MyInstance;
MyInstance << "First text" << 1 << "Second text" << 2 << "Third text" << 3;
return 0;
}
此外,我的类可以做这样的事情,这是不必要的用户:
MyInstance << "First text" << 1 << 2 << "Second text" << "Third text" << 3;
我能做些什么,以加强交流输入的性质?
关于你的评论,你需要一个参考返回到您的类,因此您可以链接在一起''<<操作。 – GWW 2011-03-02 18:15:06