【问题标题】:"Identifier is undefined" error in accessing "protected" data in sub class访问子类中的“受保护”数据时出现“标识符未定义”错误
【发布时间】:2013-02-10 23:39:09
【问题描述】:

请看下面的代码

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 错误。为什么是这样?请帮忙!

【问题讨论】:

  • display 未声明为Round 类中的方法,因此它无法访问id

标签: c++ visual-studio-2010 abstract protected


【解决方案1】:

在这个函数中:

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()

【讨论】:

  • 感谢您的回复。所以为了覆盖游戏对象中的 display() 我需要重新定义它 int Round.h?
  • @Yohan:首先你需要在Round类的定义中声明它,然后你需要为它提供一个定义。就像我的回答一样。您也可以直接在类定义中内联定义:class Round { public: /* ... */ void display() { cout &lt;&lt; "Round id: " &lt;&lt; id; } };
  • 感谢您的回复。我真的很感激:)
【解决方案2】:

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

圆形.h

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

};

圆形.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 中创建析构函数

【讨论】:

  • 感谢您的回复。来自我的 +1 :)
猜你喜欢
  • 1970-01-01
  • 2021-09-06
  • 1970-01-01
  • 2019-08-27
  • 2014-04-20
  • 2013-10-05
  • 2013-05-27
  • 2013-01-08
  • 1970-01-01
相关资源
最近更新 更多