父类可以访问C ++中派生类的对象吗?

时间:2014-10-10 15:40:22

标签: c++ class inheritance public

规则声明在公共说明符的情况下 - 派生类的对象可以被视为基类的对象(反之亦然)。那是什么意思?

所有公共元素(在任何类中)都可以被任何地方/任何地方访问吗?

这是否指的是对于父类,派生类可以访问定义为public的属性和方法。但是,如果派生类的属性和方法是公共的,那么父/基类无法访问它们?

In a public base class 
Base class members                   How inherited base class members appear in derived class
private:   x ------------------------> x is inaccessible
protected: y ------------------------> protected: y
public:    z ------------------------> public: z

但反过来呢?

3 个答案:

答案 0 :(得分:1)

这意味着如果BarFoo的派生类。

class Foo

class Bar : public Foo

所以你可以说,正如预期的那样

Foo* myFoo = new Foo;
Bar* myBar = new Bar;

您也可以FooBar,因为BarFoo

的类型
Foo* myOtherFoo = new Bar;

你不能从Bar创建Foo,这就是"派生类的对象可以被视为基类的对象(反之亦然)"装置

Bar* myOtherBar = new Foo;

答案 1 :(得分:1)

我认为正确的问题是&#34;父类可以访问C ++中派生类的成员不是对象)吗?&#34; < / p>

派生类可以访问基类的公共成员和受保护成员(数据成员和函数)。

可以从任何地方访问类的公共成员。当然,需要通过该类的实例访问它们。

  

但是,如果派生类的属性和方法是公开的,那么它们是否可以被父/基类访问?

如果您有派生类的实例,则可以是它们。然后,您可以从基类访问派生类的公共成员。


编辑:

基类成员访问派生类的公共成员的示例,反之亦然。

class Base
{
    public:
    void funcBase();
};

class Derived : public Base
{
    public:
    void funcDerived();

};

void
Base::funcBase()
{
    Derived d;
    d.funcDerived();
}

void
Derived::funcDerived()
{
    Base b;
    b.funcBase();
}

int main()
{
    Base b;
    Derived d;

    b.funcBase();
    d.funcDerived();
}

答案 2 :(得分:1)

你问:

  

父类可以访问C ++中派生类的对象吗?

是。请看下面我看过几次的模式。

您还问:

  

所有公共元素(在任何类中)都可以被任何地方/任何地方访问吗?

是的,当然。

访问派生类成员的基类的示例模式

Entity.h:

class Attribute;

class Entity
{
   public:
      Entity(Attribute* att);
      void save(FILE* fp);
      void print();

   private:
      Attribute* att_;
};

Attribute.h:

#include "Entity.h"

class Attribute : public Entity
{
   public:
      void save(FILE* fp);
      void print();

};

Entity.cc:

#include "Entity.h"
#include "Attribute.h" // Needed to access Attribute member functions

Entity::Entity(Attribute* att) : att_(att) {}

void Entity::save(FILE* fp)
{
   // Save its own data.
   //...

   // Save the Attribute
   att_->save(fp);
}

void Entity::print()
{
   // Print its own data to stdout.
   //...

   // Print the Attribute
   att_->print();
}