首页 > 解决方案 > 如何显示班级的所有信息?

问题描述

我刚开始编码,如果代码太复杂或混乱,很抱歉,任何提示都非常有用

#include <iostream>

using namespace std;


class Nacion {
public:
    string nombre;
    string tematica;
    string entorno;
    Nacion (string aNombre , string aTematica , string aEntorno){
              nombre = aNombre;
              tematica = aTematica;
              entorno = aEntorno;
    }


};

int main(){
int eligNac;
string Categoria;
string Naciones;

Nacion nacion1 ("nombre" , "tematica" , "entorno");
Nacion nacion2 ("nombre" , "tematica" , "entorno");
Nacion nacion3 ("nombre" , "tematica" , "entorno");

cout << "Elije una categoria:\n";
cout << "Naciones\n";
cout << "Campeones" << endl;
cin >> Categoria;
if (Categoria == "Naciones")
    {

    cout << "Elije una nación:\n";
    cout << "1.-Demacia\n";
    cout << "2.-Freldjord\n";
    cout << "3.-Piltover\n" << endl;

    cin >> eligNac  >> endl;
    if(eligNac = 1){
      cout << nacion1 << endl;
    }



}

这是我遇到麻烦的一行代码,我不知道在给出输入时如何显示对象的信息

标签: c++

解决方案


您可能想查看 C++ 运算符重载:https ://en.cppreference.com/w/cpp/language/operators ,特别是该operator<<部分。

在您的情况下,您可能想要执行以下操作:

std::ostream & operator<<(std::ostream & os, const Nacion & n) {
    os << n.nombre << " / " << n.tematica << " / " << n.entorno << std::endl;
    return os;
}

这为您的自定义类型定义了一个“输出运算符”,以便编译器在您要求它执行以下操作时知道该做什么:cout << nacion1;

此外,您想摆脱>> endlin cin >> eligNac >> endl;,并且您可能想要进行比较if(eligNac == 1)而不是 assignment if(eligNac = 1)


推荐阅读