【问题标题】:C++ error C2248: cannot access private member declared in SUPER classC++ 错误 C2248:无法访问在 SUPER 类中声明的私有成员
【发布时间】:2016-12-02 14:31:12
【问题描述】:

我查看了 stackoverflow 中的类似问题,但还没有找到答案。

这是我的子类声明:

class Enemy : public Entity
{
public:
    Enemy();
    ~Enemy();
}; // This is the line that shows the error...

这是我的超类声明:

class Entity
{
//Member Methods:
public:
  Entity();
  ~Entity();

bool Initialise(Sprite* sprite);
void Process(float deltaTime);
void Draw(BackBuffer& backBuffer);

void SetDead(bool dead);
bool IsDead() const;

bool IsCollidingWith(Entity& e);

float GetPositionX();
float GetPositionY();

float GetHorizontalVelocity();
void SetHorizontalVelocity(float x); 

float GetVerticalVelocity();
void SetVerticalVelocity(float y);

protected:

private:
Entity(const Entity& entity);
Entity& operator=(const Entity& entity);

//Member Data:
public:

protected:
Sprite* m_pSprite;

float m_x;
float m_y;

float m_velocityX;
float m_velocityY;

bool m_dead;

private:

};

我已经有一个名为 playership 的子类,它使用相同的结构,但它工作正常。那么哪里出了问题呢?

【问题讨论】:

  • 向我们展示导致此错误的确切代码行。
  • 这不是显示错误的相关代码。显示显示错误的代码。这是一个非常基本的错误。
  • 这是 Enemy 类中的最后一行,在 } 之后; @Ajay 提前致谢!
  • 它已更新,@TerraPass 谢谢!
  • @Wilheim Cannot duplicate。请发布实际上无法编译的代码,而不是我们不得不猜测它是什么。

标签: c++ inheritance subclass superclass


【解决方案1】:

一般你不能访问私有函数或超类的构造函数entity,当你使用类的对象时,首先调用超类的构造函数,然后调用子类的构造函数。

这里你的超类的构造函数被声明为私有的。所以,当你使用子类enemy时,超类entity的第一个构造函数被调用,然后子类enemy的构造函数被调用。

在您的代码构造函数中 superclassentity 是私有的,当您使用无法访问的子类enemy 的对象时首先调用它,这就是发生错误的原因。

【讨论】:

  • 不可理解的句子。请改写。
【解决方案2】:
private:
Entity(const Entity& entity);
Entity& operator=(const Entity& entity);

您使实体类不可复制和不可分配。但是你的敌人类没有声明这些成员函数。所以编译器有义务为你生成它们。到目前为止没问题,但我假设您随后会尝试复制敌人...

获得类似错误的最小示例:

class Entity
{
//Member Methods:
public:
  Entity();
  ~Entity();

private:
Entity(const Entity& entity);
Entity& operator=(const Entity& entity);

};

class Enemy : public Entity
{
public:
    Enemy(){}
    ~Enemy(){}
};

int main()
{
  Enemy e1, e2 = e1;
  return 0;
}

【讨论】:

  • 那么我可以在 Enemy 类中做些什么来避免这个错误呢? @StoryTeller
  • @Wilheim,为EnemyEntity 明确定义一个有效的复制c'tor(和赋值运算符)。
猜你喜欢
  • 2014-01-10
  • 2012-11-15
  • 1970-01-01
  • 2013-07-28
  • 2011-09-06
  • 2015-03-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多