【发布时间】:2012-04-30 02:24:07
【问题描述】:
以下是逐字逐句的说明:
字符串插入/提取运算符(>)需要在 MyString 对象中重载。这些运算符还需要能够进行级联操作(即 cout > String1 >> String2)。字符串插入运算符 (>>) 将读取以行尾字符 (\n) 或 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& 运算符>>(istream& input, MyString& rhs);
从 main.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 和输入的情况下做到这一点
【问题讨论】:
-
那是
stream extraction operator。 -
其实是右移算子,但是流恰好把它当做所谓的“提取算子”
-
@SethCarnegie,是的,我将其与“插入运算符”的使用进行比较
标签: c++ string operator-overloading insertion