重载级联插入运算符
overloading cascading insertion operator
以下是逐字说明:
字符串插入/提取运算符(<<和>>(需要在 MyString 对象中重载。这些运算符还需要能够级联操作(即 cout <<String1 <<String2 或 cin>> String1>> String2(。字符串插入运算符 (>>( 将读取以行尾字符 (( 或 256 个字符结尾的整行字符。超过 256 个字符的输入行将仅限于前 256 个字符。
有了这个,这就是我到目前为止得到的代码:
在我的.cpp文件中:
istream& MyString::operator>>(istream& input, MyString& rhs)
{
char* temp;
int size(256);
temp = new char[size];
input.get(temp,size);
rhs = MyString(temp);
delete [] temp;
return input;
}
在我的 .h 文件中:
istream& operator>>(istream& input, MyString& rhs(;
从主文件调用.cpp:
MyString String1;
const MyString ConstString("Target string"); //Test of alternate constructor
MyString SearchString; //Test of default constructor that should set "Hello World"
MyString TargetString (String1); //Test of copy constructor
cout << "Please enter two strings. ";
cout << "Each string needs to be shorter than 256 characters or terminated by
/.n" << endl;
cout << "The first string will be searched to see whether it contains exactly the second string. " << endl;
cin >> SearchString >> TargetString; // Test of cascaded string-extraction operator<<
我得到的错误是:istream&MyString::operator>>(std::istream&,MyString&(必须只接受一个参数
我该如何纠正此问题?我对如何在没有 rhs 和输入的情况下执行此操作感到非常困惑
您必须将operator>>
创建为非成员函数。
就像现在一样,您的函数需要三个参数:隐式调用对象、istream&
和 MyString& rhs
。但是,由于operator>>
是一个二元运算符(它恰好需要两个参数(,因此这不起作用。
执行此操作的方法是使其成为非成员函数:
// prototype, OUTSIDE the class definition
istream& operator>>(istream&, MyString&);
// implementation
istream& operator>>(istream& lhs, MyString& rhs) {
// logic
return lhs;
}
这样做(非成员函数(是你必须做所有运算符的方式,你希望你的类在右侧,以及你不能修改的类在左侧。
另请注意,如果要让该函数访问对象的private
或protected
成员,则必须在类定义中friend
声明它。
相关文章:
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 我的运算符重载是否有效<<(流插入)左操作数不是 ostream
- 重载嵌套结构/类的流插入运算符
- 屏幕插入运算符<<的运算符过载问题
- 类方法的C++插入运算符
- 在设计方面:重载vector类型的类成员的插入运算符
- 类重载运算符 '<' 插入指向该对象集的共享指针时不调用
- std::map 索引运算符与插入方法的性能
- 我在C++中遇到插入运算符错误
- 基类和派生类的虚拟插入运算符重载
- 如何在 std::map<const int、int> C++ 中重载插入运算符>>?
- 派生类 插入和提取运算符重载以及基类与派生类之间的强制转换
- 如何将重载>>运算符中输入的值插入到资源库
- 插入运算符的过载与使用二传手功能相比
- Visual Studio 15:重载"<<" C++中的插入运算符
- 使用 std::stringbuf 进行缓冲的效果,同时通过插入运算符'<<'执行写入
- 为什么当我使用额外的括号而不使用运算符重载时,插入运算符在 std::cout 中给出不同的结果?
- 带有指针的重载插入/提取运算符
- 编译器在遇到提取或插入运算符时处理信息(字符串、操纵器等)的顺序是什么?
- 插入运算符无法使用矢量,我不知道为什么