【问题标题】:C++ Child Class with a Child Member带有子成员的 C++ 子类
【发布时间】:2019-03-20 05:43:01
【问题描述】:

我正在努力记住我的 C++。我不知道该怎么做。我有一个父类和一个子类。父类有一个成员,该成员是另一个不同对象的实例的引用……子类具有对该其他对象的子版本的引用。

基本上,我希望有一个 Parent 类,它表示它将拥有什么样的成员,以及全局成员函数以及必须由子类定义的虚拟函数。

但是,某些子类可能需要特定类型的成员对象,它继承父类型。这是一个例子。

我们有一个 Person,它被 BigPerson 继承。 我们有一个 Home,它由 BigHome 继承。

我希望 Person 类表明它有一个 Home,但是 BigPerson 应该有一个 BigHome(它仍然是一个 Home)。

#include <iostream>

using namespace std;


class Home {
    public:

    virtual string sayHome()
    {
        cout << "Home";
    }
};

class BigHome : public Home
{
    public:
    int num = 5;
    virtual string sayHome() override
    {
        cout << "Big Home " << this->num;
    }

};


class Person
{
    public:

    Home& home;

    Person(Home& home) : home(home) {}

    virtual void sayHello()
    {
        cout << "hello";
    }

    virtual void talk()
    {
        this->sayHello();
        cout << ", I have a ";
        this->home.sayHome();
        cout << endl;
    }
};

class BigPerson : public Person
{
    public:

    BigPerson(BigHome& bigHome) : Person(bigHome) { }

    virtual void sayHello() override
    {
        cout << "big hello " << home.num;
    }
};




int main()
{
    Home home;
    BigHome bigHome;
    bigHome.num = 7;
    //*
    Person p(home);
    BigPerson bp(bigHome);
    //*
    p.talk();    
    bp.talk();
    //*/
    return 0;
}

我得到的错误是:

main.cpp: In member function ‘virtual void BigPerson::sayHello()’:
main.cpp:65:44: error: ‘class Home’ has no member named ‘num’
         cout << "big hello " << this->home.num;
                                            ^

【问题讨论】:

  • 注意:virtual string sayHome() 承诺返回,string,但没有。这可能会在运行时产生非常不幸的结果。
  • 啊是的。我写了这个例子,错过了那部分。

标签: c++ class inheritance


【解决方案1】:

class Person 具有 home 类型的成员 class Home &amp;。在编译时绑定不知道它是指Home 还是BigHome 对象,因此不可能指向BigHome 的成员。

一种可能的解决方法是使用dynamic castassert 进行类型检查并使用static cast

BigHome *p = dynamic_cast<BigHome *>(&home);
assert(p != nullptr);
cout << "big hello " << p->num;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-13
    • 2011-11-03
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    • 1970-01-01
    相关资源
    最近更新 更多