Max*_*xpm 4 c++ oop class operator-overloading stream
我正在制作一个使用的简单课程operator<<
.它将存储两个并行的数据数组,每个数据类型具有不同(但已知)的数据类型.这个想法是最终的界面看起来像这样:
MyInstance << "First text" << 1 << "Second text" << 2 << "Third text" << 3;
Run Code Online (Sandbox Code Playgroud)
这将使数组看起来像这样:
StringArray: | "First text" | "Second text" | "Third text" |
IntArray: | 1 | 2 | 3 |
Run Code Online (Sandbox Code Playgroud)
我可以处理检查输入的逻辑,以确保一切都匹配,但我对技术细节感到困惑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;
}
Run Code Online (Sandbox Code Playgroud)
此外,我班级的用户可以做这样的事情,这是不需要的:
MyInstance << "First text" << 1 << 2 << "Second text" << "Third text" << 3;
Run Code Online (Sandbox Code Playgroud)
我可以做些什么来强制输入的交替性质?
之所以ostream
运营商返回一个参考ostream
,并有所帮助你的情况的原因返回一个参考MyClass
的是,像一个表达式A << B << C
总是被解释一样(A << B) << C
.也就是说,无论第一个重载运算符返回什么,都会成为下一个运算符调用的左侧.
现在,如果您希望表达式MyInstance << "First text" << 1 << 2
产生编译器错误,则需要确保在前两个<<
运算符之后返回的类型是不能使用另一个int调用的类型.我认为这样的事情可能会做你想要的(感谢@Pete Kirkham提出了一个很好的改进意见):
struct MyClass_ExpectInt;
class MyClass {
private:
friend MyClass& operator<<(const MyClass_ExpectInt&, int);
void insert_data(const std::string& StringData, int IntData);
// ...
};
struct MyClass_ExpectInt {
MyClass& obj_ref;
std::string str_data;
explicit MyClass_ExpectInt( MyClass& obj, const std::string& str )
: obj_ref( obj ), str_data( str ) {}
};
MyClass_ExpectInt operator<<( MyClass& obj, const std::string& StringData )
{
// Do nothing until we have both a string and an int...
return MyClass_ExpectInt( obj, StringData );
}
MyClass& operator<<( const MyClass_ExpectInt& helper, int IntData )
{
helper.obj_ref.insert_data( helper.str_data, IntData );
return helper.obj_ref;
}
Run Code Online (Sandbox Code Playgroud)
这些将是operator<<
您定义的唯一两个重载函数MyClass
.这样一来,每次调用时operator<<
,编译器切换返回类型MyClass&
来MyClass_ExpectInt
反之亦然,并通过了"错误"之类的数据来operator<<
是绝不允许.
归档时间: |
|
查看次数: |
285 次 |
最近记录: |