如何正确重载 << 操作数以产生所需的结果?

Vul*_*rse 0 c++ arrays class operator-overloading

https://leetcode.com/explore/learn/card/fun-with-arrays/521/introduction/3294/

我正在学习有关数组的 Leetcode 课程,并尝试使用 C++ 进行学习,就像他们使用 Java 一样,但我很难通过这一部分。我只想从我制作的图鉴数组中读取项目。

我得到的最初错误是:

No operator << matches these operands.
Array.cpp(16,15) operand types are std::ostream << Pokemon
Run Code Online (Sandbox Code Playgroud)

然后我尝试重载 << 运算符,因为我看到其他人在这里询问,但我没有得到我想要的输出。当我按原样编译程序时,没有任何打印。

有人可以解释我可以做什么来获得所需的输出吗?

Cyndaquill 是 5 级火焰类型

另外,有人可以解释一下,或者给我指出可以以简单而不冗长的方式解释运算符重载的人的方向吗?我在 StackOverflow 上看到的很多内容都过于冗长和混乱。也许是因为我是 C++ 新手,但仍然如此。

数组.cpp

#include <iostream>
#include "Array_Header.hpp"

int main() {
    
    Pokemon pokeDex[15];

    Pokemon Cyndaquill = Pokemon("Cyndaquill", 5, "Fire");
    Pokemon Totodile = Pokemon("Totodile", 5, "Water");
    Pokemon Chikorita = Pokemon("Chikorita", 5, "Grass");

    pokeDex[0] = Cyndaquill;
    pokeDex[1] = Totodile;
    pokeDex[2] = Chikorita;

    std::cout << pokeDex[0];
    std::cout << pokeDex[1];
    std::cout << pokeDex[2];
    std::cout << pokeDex[3];

}
Run Code Online (Sandbox Code Playgroud)

Array_Header.hpp

#include <string>

class Pokemon {

    public:

    //variable declarations
    std::string name;
    int level;
    std::string type;

    //Constructor for the DVD class
    Pokemon(std::string name, int level, std::string type);
    Pokemon() = default;

    //toString function declaration
    std::string toString();

    friend std::ostream& operator<<(std::ostream& os, const Pokemon& obj) 
    { 
        return os;
    };

};
Run Code Online (Sandbox Code Playgroud)

数组头.cpp

#include "Array_Header.hpp"

//Constructor Definition
Pokemon::Pokemon(std::string name, int level, std::string type){
    this->type = type;
    this->level = level;
    this->name = name;
};


//toString function definition
std::string Pokemon::toString(){
    return this->name + " is a " + this->type + " type at level " + std::to_string(level) + "\n";
};
Run Code Online (Sandbox Code Playgroud)

小智 8

<<用于打印到std::ostream类型对象的运算符重载Pokemon除了返回参数之外什么也不做os。您需要在此处添加打印逻辑,如下所示:

friend std::ostream& operator<<(std::ostream& os, const Pokemon& obj) 
{
    os << obj.toString();
    return os;
};
Run Code Online (Sandbox Code Playgroud)

  • 这就是为什么你应该通过学习 C++ 来学习 C++,而不是通过学习 Java 并尝试编写类似的东西。Java 并没有真正与 C++ 中的“const”直接等效的东西。实际要做的事情是保持“operator&lt;&lt;”的签名不变,但将“toString”更改为“const”成员函数,以便可以从“const Pokemon”对象调用它。 (2认同)