Getter seg fault

Getter seg fault

本文关键字:fault seg Getter      更新时间:2023-10-16

我做了一个简单的getter,他们返回了seg错误,我不知道问题出在哪里:

有一个包含两个玩家和一个托盘的类"游戏":

> #ifndef PARTIE_H
> #define PARTIE_H
> 
> #include <string>
> #include <iostream>
> 
> class partie {
>     class joueur * joueur1;
>     class joueur * joueur2;
>     class plateau * jeu;
> 
> public:
>     partie();
>     void initialize(std::string nomj1, std::string nomj2, int tailleplateau);
>     int info();
>     ~partie();
> 
> };
> 
> #endif // PARTIE_H

.cpp :

> #include "partie.h"
> #include "joueur.h"
> #include "plateau.h"
> #include <string>
> #include <iostream>
> 
> partie::partie() {
>     plateau * jeu = new plateau(0);
>     joueur * joueur1 = new joueur("test", 1);
>     joueur * joueur2 = new joueur("test2", 2);
> 
> }
> 
> void partie::initialize(std::string nomj1, std::string nomj2, int
> tailleplateau) {
>     plateau * jeu = new plateau(tailleplateau);
>     joueur * joueur1 = new joueur(nomj1, 1);
>     joueur * joueur2 = new joueur(nomj2, 2); }
> 
> int partie::info() {   return joueur1->getIdentifiant();
> 
> }
> 
> 
> partie::~partie() {
> 
> }

班级玩家:

> #ifndef JOUEUR_H
> #define JOUEUR_H
> #include <string>
> #include <iostream>
> 
> class joueur {
>     std::string nom;
>     int identifiant;
> 
> public:
>     joueur();
>     joueur(std::string name, int num);
>     std::string getName();
>     int getIdentifiant(); };
> 
> #endif // JOUEUR_H

.cpp

> #include "joueur.h"
> #include <string>
> #include <iostream>
> 
> joueur::joueur() {
>     this->nom="DEFAULT";
>     this->identifiant=0; }
> 
> joueur::joueur(std::string name, int num) {
>     this->nom=name;
>     this->identifiant=num; }
> 
> int joueur::getIdentifiant() {
>     return identifiant; }
> 
> std::string joueur::getName() {
>     return nom; }

有人看到错误吗? 谢谢你的帮助

有很多错误,例如缩进是一个很大的错误。 请通过 CLANG 格式或 astyle 运行您的代码,它会更容易审查。

当你
  • 不需要它时,不要使用它>,这不是Java。
  • 不要与局部变量和类成员混淆(这是你的错误)
plateau * jeu = new plateau(tailleplateau);
joueur * joueur1 = new joueur(nomj1, 1);
joueur * joueur2 = new joueur(nomj2, 2); }

在这里,您创建了一个名为 jeu、jouer1 和 jouer2 的局部变量,但看起来您在类中也声明了这些变量,因此修复很简单:

jeu = new plateau(tailleplateau);
joueur1 = new joueur(nomj1, 1);
joueur2 = new joueur(nomj2, 2);

不要重新声明它们。 :)

更多提示: - C++不是Java,你通常不需要新的东西: - 无需在堆上添加您的 joeurs/plateau,您可以安全地在堆栈上声明它们(即,没有指针) - 如果你认为你真的应该在堆(指针)上创建它们,不要使用原始指针,使用智能指针(你的应该看起来像unique_ptr)

class Game {
Game() : player1(make_unique<Player>());
}
private:
std::unique_ptr<Player> player1;
};

这应该可以消除您的内存问题。现在,如果它继续发生,请发布调试输出或回溯。