【问题标题】:Having public member variables access private members of the same class in C++让公共成员变量访问 C++ 中同一类的私有成员
【发布时间】:2019-11-16 03:36:43
【问题描述】:

我正在尝试创建一个类,其中函数更改该类的私有成员的值,但我不断收到“使用未声明的标识符”的错误。我想如果函数是类成员,那么他们可以访问私有成员?

我的代码供参考

建筑.h

#ifndef BUILDING_H
#define BUILDING_H
#include "Point2D.h"
#include "GameObject.h"

class Building : public GameObject
{

private:
    unsigned int pokemon_count;

Building();
Building(char,int, Point2D);

public:
    void AddOnePokemon();
    void RemoveOnePokemon();
    void ShowStatus();
    bool ShouldBeVisible();

};

#endif

建筑.cpp

#include "Building.h"
#include "GameObject.h"
#include <iostream>
using namespace std;

Building::Building()
{
    display_code = 'B';
    location;
    id_num = ' ';
    state = '0';
    pokemon_count = 0;
    cout << "Building default constructed";
}

Building::Building(char in_code,int in_id, Point2D in_loc)
{
    id_num = in_id;
    location = in_loc;
    display_code = in_code;
    state = '0';
    cout << "Building constructed";
}

void AddOnePokemon()
{
    pokemon_count = pokemon_count+1;
}

void ReturnOnePokemon()
{
    pokemon_count = pokemon_count-1;
}

void ShowStatus()
{
    cout << "\"(" << pokemon_count << "pokemon is/are in this building";
}

【问题讨论】:

    标签: c++ class inheritance


    【解决方案1】:

    您的函数超出了您的课程范围。

    在函数前面添加类名,这应该可以工作:

    void Building::AddOnePokemon()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-08
      • 2015-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-04
      • 2014-10-27
      相关资源
      最近更新 更多