You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何调用用户输入名称的Personnage类对象的afficherEtat方法?

问题:通过用户输入名称调用Personnage类方法失败

编译报错:

error: 'std::__cxx11::string {aka class std::__cxx11::basic_string<char>}' has no member named 'afficherEtat'|

原错误代码

Personnage.hpp

#ifndef PERSONNAGE_HPP_INCLUDED
#define PERSONNAGE_HPP_INCLUDED
#include <iostream>
#include <string>
class Personnage { 
public: 
    Personnage(std::string nomPerso); 
    void afficherEtat() const; 
private: 
    std::string m_nomPerso;    
};  
#endif 

Personnage.cpp

#include "Personnage.hpp"
#include <string>
using namespace std;
Personnage::Personnage(string nomPerso) : m_nomPerso(nomPerso) {}
void Personnage::afficherEtat() const
{    
    cout << "Le nom : " << m_nomPerso << endl;
}

main.cpp

#include <iostream>
#include <string>
#include "Personnage.hpp" 
#include <vector>

int main()
{
    string creaPersoFini("y");
    int nombrePerso(0);
    vector<string> tableauNomPerso;
    string nomPerso;

    while(creaPersoFini!="n")
    {
        cout << "Entrez le nom du personnage : ";
        cin >> nomPerso;
        tableauNomPerso.push_back(nomPerso);
        Personnage(nomPerso);
        cout << "Voulez vous creer un autre personnage ? y/n ";  
        cin >> creaPersoFini;
        nombrePerso++;
    }

    for(int i=0; i<=nombrePerso; i++)
    {
        cout << endl;
        cout << tableauNomPerso[i] << endl;
        nomPerso = tableauNomPerso[i];
        nomPerso.afficherEtat();                // 错误位置
        cout << endl;
    }
return 0;
}

问题根源

  1. 仅存储了对象名称的字符串,而非Personnage对象本身。字符串类型没有afficherEtat()方法,因此编译报错。
  2. 原代码中Personnage(nomPerso);只是创建了一个临时对象,语句执行完后临时对象就被销毁,没有保留任何实例。
  3. 循环条件i<=nombrePerso会导致越界访问,因为vector的有效索引范围是0到size()-1。

修正后的main.cpp代码

无需修改Personnage.hpp和Personnage.cpp,仅修改main.cpp:

int main()
{
    string creaPersoFini("y");
    vector<Personnage> tableauPerso;    // 存储Personnage对象,而非字符串
    string nomPerso;

    while(creaPersoFini!="n")
    {
        cout << "Entrez le nom du personnage : ";
        cin >> nomPerso;
        Personnage newP(nomPerso);              // 创建Personnage对象
        tableauPerso.push_back(newP);           // 将对象存入vector
        cout << "Voulez vous creer un autre personnage ? y/n ";
        cin >> creaPersoFini;
    }

    for(int i=0; i<tableauPerso.size(); i++)        // 修正循环条件,避免越界
    {
        cout << endl;
        tableauPerso[i].afficherEtat();
        cout << endl;
    }
return 0;
}

内容的提问来源于stack exchange,提问作者Iv_Vae

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 18:50:24