首页 > 解决方案 > 如何调用用于重载运算符“<<”的友元函数?

问题描述

.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;
}

我没有拿出我的构造函数,因为我希望我能保护我的代码

主文件

  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 

当我删除好友功能时。我的输出还是一样的。我只是不知道为什么当我调用显示函数时,运算符 << 并没有重载

标签: c++

解决方案


  1. Your title has a possible typo? You are overloading operator<< in code, but you are asking about overloading operator>>.
  2. If my guess of the typo is right, it's because you did not called ostream& operator<< (ostream&, MyString&); at all.
    In your void MyString::displayState( ostream& out ) function, you are calling
out << "Data: " << this->data << endl;

which is calling std::ostream& operator<<(std::ostream&, const char*)

EDIT for addition: As for how to call your function, you defined that operator<< to accept an ostream& and MyString&. So you simply call it by std::cout<<testStr2; in your main().


推荐阅读