【问题标题】:overloading cascading insertion operator重载级联插入运算符
【发布时间】: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


【解决方案1】:

您必须将operator&gt;&gt; 创建为非成员函数。

现在,您的函数需要三个参数:隐式调用对象、istream&amp;MyString&amp; rhs。但是,由于operator&gt;&gt; 是一个二元运算符(它只需要两个参数),这将不起作用。

这样做的方法是使其成为非成员函数:

// prototype, OUTSIDE the class definition
istream& operator>>(istream&, MyString&);

// implementation
istream& operator>>(istream& lhs, MyString& rhs) {
    // logic

    return lhs;
}

这样做(非成员函数)是您必须执行所有运算符的方式,您希望您的类位于右侧,而您无法修改的类位于左侧。

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

【讨论】:

  • @user1363061 如果您的问题没有得到解决,那么您不应将其标记为答案。您必须生成一个我们可以编译并得到相同错误的测试用例。
  • 哈!我知道了!太感谢了!现在我确定我可以对插入运算符做同样的事情
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-10
  • 2015-01-07
  • 1970-01-01
  • 2017-03-22
  • 1970-01-01
  • 1970-01-01
  • 2012-05-09
相关资源
最近更新 更多