.h文件
class MyString{
private:
int size;
int capacity;
char *data;
public:
MyString( );
MyString(const char *);
void displayState( ostream &out );
friend ostream& operator<< (ostream&, MyString&);
};
.cpp
void MyString::displayState( ostream& out ){
out << "Size: " << this->size << endl;
out << "Capacity: " << this->capacity << endl;
out << "Data: " << this->data << endl;
}
ostream& operator << (ostream& out, MyString& myStr){
for (int i = 0; i < myStr.size; i++){
out << myStr.data[i]<<" ";
}
return out;
}
我没有淘汰我的构造函数,因为我希望我可以保护我的代码
main.cpp
char array[20] = {'1','2','4','g','1',
'2','6','b','v','c',
'b','c','b','q','b',
'p','b','q','m'};
MyString testStr2(array);
testStr2.displayState(cout);
输出是
Size: 19
Capacity: 20
Data: 124g126bvcbcbqbpbqm
我的代码想让我的输出像
Size: 19
Capacity: 20
Data: 1 2 4 g 1 2 6 b v c b c b q b p b q m
当我删除好友功能时。我的输出仍然相同。我只是不知道为什么当我调用显示函数时,运算符<<并没有过载
最佳答案
operator<<
,但您正在询问有关重载operator>>
的问题。 ostream& operator<< (ostream&, MyString&);
。在
void MyString::displayState( ostream& out )
函数中,您正在调用out << "Data: " << this->data << endl;
正在调用
std::ostream& operator<<(std::ostream&, const char*)
编辑以补充内容:至于如何调用函数,您定义了
operator<<
来接受ostream&
和MyString&
。因此,您只需通过std::cout<<testStr2;
进行调用在您的
main()
中。
关于c++ - 如何调用用于重载运算符 “<<”的好友函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60023231/