c++ - 如何调用用于重载运算符 “<<”的好友函数?

标签 c++

.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/

    相关文章:

    适用于 iOS 的 Objective-C 中的 C++ 代码

    c++ - Boost::python 静态方法返回类的实例

    c++ - 如何根据模板参数创建一个方法const?

    c++ - C++ 中的多态性(意外行为)

    C++ STL 101 : Overload function causes build error

    c++ - C++ 中的正则表达式跳过

    c++ - 大型 POD 作为元组进行排序

    c++ - 使用 DFS 检查无向图中的循环?

    c++ - Visual Studio 的 CRT 中的 `_setmode` 如何与 `std::wcout` 交互?

    c++ - 使用 const 对象 move 语义