访问子类中的"protected"数据时"Identifier is undefined"错误
"Identifier is undefined" error in accessing "protected" data in sub class
请看下面的代码
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
相关文章:
- Why is UINT32_MAX + 1 = 0?
- C++错误:"error: int aaa::bbb is protected within this context"
- 创建具有 new in 函数和"this is nullptr"异常的对象
- 使用 cmake 的 Linux 终端上的"Conversion to non-scalar type is requested"错误
- 我看到"use of undeclared identifier"错误,有人可以告诉我如何解决它吗?
- Is !NaN not a NaN?
- Directx 11 - CompileFromFile() is not compiling
- Centos7 g++ "to_string is not in a member of std"
- "Unable to start debugging. No process is associated with this object." - 在Visual Studio Code中使用GDB
- Where is std::hardware_destructive_interference_size?
- 为什么即使在定义之后仍存在"Identifier is undefined error "?
- 如何解决"identifier 'gets'/'clrscr' is undefined"问题?
- 字符串返回功能不起作用 - 'identifier is underfined'
- 使用结构体的简单"identifier 'xxx' is undefined"
- 包括 fstream,但"ifstream not found"和"identifier is undefined"
- C++ ~ 在客户端中调用函数会给出错误:"identifier ____ is undefined"
- Unreal Engine 4.19 C++Undeclared Identifier错误,但它的代码是IS声明的
- 为什么我不能在我的程序中声明一个字符串:"string is undeclared identifier"
- 访问子类中的"protected"数据时"Identifier is undefined"错误
- 如何修复简单C++应用程序中的"identifier is undefined"错误?