访问子类中的"protected"数据时"Identifier is undefined"错误

"Identifier is undefined" error in accessing "protected" data in sub class

本文关键字:Identifier is undefined 错误 protected 子类 访问 数据      更新时间:2023-10-16

请看下面的代码

GameObject.h

#pragma once
class GameObject
{
protected:
    int id;
public:
    int instances;
    GameObject(void);
    ~GameObject(void);
    virtual void display();
};

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

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

Round::Round(void)
{
}

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

我在Round类中得到'id' : undeclared identifier错误。为什么会这样?请帮助!

在此函数中:

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

你试图访问非成员函数中名为id的变量。编译器无法解析该名称,因为id不是任何全局变量或局部变量的名称,因此您会得到一个错误,抱怨没有声明标识符。

如果你想让display()成为Round()的成员函数,你应该这样声明它:

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

是这样定义的:

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

这样,函数Round::display()将覆盖虚函数GameObject::display()

您在Round.cpp文件中声明了一个名为display的全局作用域方法。像这样编辑标题和cpp:

Round.h

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

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;
}

注意-你应该把GameObject中的析构函数设置为virtual