重载级联插入运算符

overloading cascading insertion operator

本文关键字:运算符 插入 级联 重载      更新时间:2023-10-16

以下是逐字说明:

字符串插入/提取运算符(<<和>>(需要在 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;
}

这样做(非成员函数(是你必须做所有运算符的方式,你希望你的类在右侧,以及你不能修改的类在左侧。

另请注意,如果要让该函数访问对象的privateprotected成员,则必须在类定义中friend声明它。