【问题标题】:Call inherited method using some "specialized" fields使用一些“专门”字段调用继承的方法
【发布时间】:2017-08-22 18:13:16
【问题描述】:

例如:

struct A {
    ~A() {
        cout << me << ": destructor" << endl;
    }
    const string me = "A";
};

struct B : A {
    const string me = "B";
};

int main() {
    {
        A a;
        B b;
    }
    cout << "----\n";
    return 0;
}

对不起,新手问题,我只是想知道以下输出:

A: destructor
A: destructor
----

在第二行我期待B: destructor。你能解释一下为什么吗?如何在不重写析构函数的情况下修改代码才能看到预期的结果?

【问题讨论】:

  • A::me 与B::me 完全无关。它们是独立的变量,A 对B::me 一无所知。

标签: c++ inheritance code-reuse


【解决方案1】:

声明 B::me 会影响 A::me,但 A::~A 显然使用了 A::me。 (您应该阅读更多关于 ctors 和 dtors 的内容,特别是为什么不应该在 ctors 和 dtors 中调用虚函数以便更深入地理解)。至于应该如何更正示例:

struct A{
  string me;
  A(string str = "A") : me(str){}
  ~A(){cout<<me<<endl;}
}

struct B : A {
  B(string str = "B") : A(str){}
}

【讨论】:

    猜你喜欢
    • 2012-01-15
    • 1970-01-01
    • 2010-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-23
    • 2015-09-18
    • 2016-08-14
    相关资源
    最近更新 更多