【问题标题】:C++ Error: class/object was not declared in this scopeC++ 错误:未在此范围内声明类/对象
【发布时间】:2020-03-18 08:09:14
【问题描述】:

我对 C++ 完全陌生,我正在尝试制作一个非常简单的基于文本的战斗系统,但我不断收到错误消息:“objPlayer 未在此范围内声明”。

所有代码都写在main()函数之前:

#include <iostream>

using namespace std;


    //DECLARE THE UNIT CLASS
    class generalUnit {
    public:
    int health; //the amount of health the unit has
    };


    //DECLARE THE PLAYER THOUGH THE UNIT CLASS 
    void generatePlayer() {
    generalUnit objPlayer;
    int objPlayer.health = 100;
    }


    //DECLARE AND INITIALIZE ALL COMMANDS
    //CHECK STATS
    void comCheckStats() {
        cout << objPlayer.health << endl;
    }

【问题讨论】:

  • 如您所见,您仅在 generatePlayer 函数中声明了它。它只存在于其中,别无他处。
  • 啊当然。我试图删除该函数并且错误消失了,但是现在它说“预期的初始化程序之前'。'令牌。所以我又把函数放回去了。有没有办法让 objPlayer 对其余代码可见,就像在类中使用“public”时一样?
  • 哈哈我去看看,谢谢

标签: c++ class object


【解决方案1】:

您不必在指向您正在使用的类的对象的类中创建变量。它已经被声明并被称为this

使用运算符-&gt;,您可以从this 访问成员变量。像这样:

#include <iostream>
#include <string>

using namespace std;

class Player
{
public:
    int health;

    // this is constructor
    Player(int health_at_start)
    {
        this->health = health_at_start;
    }

    void comCheckStats()
    {
        cout << this->health << '\n';
    }
};

int main()
{
    // create player with 100 health
    Player p1(100);
    p1.comCheckStats();

    // create player with 200 health
    Player p2(200);
    p2.comCheckStats();
}

如您所见,我正在使用名为 constructor 的东西来创建 Player 的新实例。它只是没有返回类型的函数,声明与类同名。它初始化成员变量的起始数据,您也可以将一些值传递给它。

【讨论】:

  • 非常感谢您的精彩解释! :D 我相信我有一些东西要学哈哈
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-15
  • 2022-01-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多