简体   繁体   English

访问子类中的“受保护”数据时出现“标识符未定义”错误

[英]“Identifier is undefined” error in accessing “protected” data in sub class

Please have a look at the following code 请看下面的代码

GameObject.h 游戏对象

#pragma once
class GameObject
{
protected:
    int id;

public:
    int instances;

    GameObject(void);
    ~GameObject(void);

    virtual void display();
};

GameObject.cpp GameObject.cpp

#include "GameObject.h"
#include <iostream>

using namespace std;

static int value=0;
GameObject::GameObject(void)
{
    value++;
    id = value;
}


GameObject::~GameObject(void)
{
}

void GameObject::display()
{
    cout << "Game Object: " << id << endl;
}

Round.h 回合

#pragma once
#include "GameObject.h"
class Round :
    public GameObject
{
public:
    Round(void);
    ~Round(void);


};

Round.cpp Round.cpp

#include "Round.h"
#include "GameObject.h"
#include <iostream>

using namespace std;


Round::Round(void)
{
}


Round::~Round(void)
{
}

void display()
{
    cout << "Round Id: " << id;
}

I am getting 'id' : undeclared identifier error in Round class. 我收到'id' : undeclared identifier Round类中'id' : undeclared identifier错误。 Why is this? 为什么是这样? Please help! 请帮忙!

In this function: 在此功能中:

void display()
{
    cout << "Round Id: " << id;
}

You are trying to access a variable named id inside a non-member function. 您正在尝试在非成员函数中访问名为id的变量。 The compiler cannot resolve that name, because id is not the name of any global nor local variable, therefore you get an error complaining that the identifier was not declared. 编译器无法解析该名称,因为id既不是全局变量也不是局部变量的名称,因此您会收到一个错误消息,抱怨未声明标识符。

If you meant to make display() a member function of Round() , you should have declared it as such: 如果要让display()成为Round() display()的成员函数,则应这样声明:

class Round : public GameObject
{
public:
    Round(void);
    ~Round(void);
    void display(); // <==
};

And defined it this way: 并以这种方式定义它:

void Round::display()
//   ^^^^^^^
{
    ...
}

This way, function Round::display() would override the virtual function GameObject::display() . 这样, Round::display()函数将覆盖虚拟函数GameObject::display()

You declared a globally scoped method named display in your Round.cpp file. 您在Round.cpp文件中声明了一个名为display的全局范围的方法。 Edit your header and cpp like this: 像这样编辑标题和cpp:

Round.h 回合

#pragma once
#include "GameObject.h"
class Round :
    public GameObject
{
public:
    Round(void);
    virtual ~Round(void);
    virtual void display(void);

};

Round.cpp Round.cpp

#include "Round.h"
#include "GameObject.h"
#include <iostream>

using namespace std;


Round::Round(void)
{
}


Round::~Round(void)
{
}

void Round::display()
{
    cout << "Round Id: " << id;
}

Note - you should make the destructor in GameObject virtual 注意-您应该将GameObject中的析构函数设为虚拟

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM