首页 > 解决方案 > c++中的作用域和继承

问题描述

我想知道为什么编译器不允许第二次使用“print_all”函数。

如果编译器允许的话,我必须举一个可能发生的坏事的例子。

#include <iostream>
#include <list>
using std::list;
class foo {
    class bar : public foo {
        static void print_all(list<foo *> &L) {
            list<foo *> LF;
            list<bar *> LB;
                print_all(LF); // works fine
                print_all(LB); // static semantic error

        }
    };
};

标签: c++inheritancescopestatic

解决方案


list<foo *> is an unrelated type to list<bar *>. The function is specified to accept one, but not the other.

But class bar inherits from class foo

That is irrelevant, because the argument of your function isn't foo&. What's relevant is whether list<bar *> inherits list<foo *>. It doesn't. std::list does not have a base class.


推荐阅读