gpt4 book ai didi

c++ - 重载级联插入运算符

转载 作者:行者123 更新时间:2023-11-28 08:05:31 24 4
gpt4 key购买 nike

这里是逐字说明:

String insertion/extraction operators (<< and >>) need to be overloaded within the MyString object. These operators will also need to be capable of cascaded operations (i.e., cout << String1 << String2 or cin >> String1 >> String2). The string insertion operator (>>) will read an entire line of characters that is either terminated by an end-of-line character (\n) or 256 characters long. An input line that exceeds 256 characters will be limited to only the first 256 characters.

到目前为止,这是我得到的代码:

在我的 .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);

从 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&)â must take exactly one argument

我该如何纠正这个问题?我对如何在没有 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在你的类定义中。

关于c++ - 重载级联插入运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10377830/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com