c++ - 如何显示班级的所有信息?
问题描述
我刚开始编码,如果代码太复杂或混乱,很抱歉,任何提示都非常有用
#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++ 运算符重载: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;
此外,您想摆脱>> endl
in cin >> eligNac >> endl;
,并且您可能想要进行比较if(eligNac == 1)
而不是 assignment if(eligNac = 1)
。
推荐阅读
- amazon-web-services - AWS 开发工具包 - 按部分名称搜索图像
- vue.js - 如何动态删除谷歌地图?
- git - Git 没有合并我的更改,尽管它说合并已成功
- python - 错误:在 PATH 中找不到命令((来自 my_script)
- apache-flink - 尝试从保留的检查点启动 Flink 作业时出错
- r - 在 Windows 网络共享问题上创建 RStudio 项目
- pyspark - 如何限制按列分区范围内的最大分区数
- excel - VBA将文件夹中的所有文件导入Access
- kubernetes - AKS 中的 Kubectl 配置
- c++ - 使用 FileSource 和 FileSink 将 AES IV 写入文件