繁体   English   中英

虚拟功能...为什么要私有?

[英]virtual functions…why is this private?

我正在尝试使以下代码起作用...

#include <list>

template <typename T>
class container{
public:
    virtual T func_x(){
        T temp;
        //do stuff with list<t> test
        return temp;
    }
private:
    std::list<T> test;
};

template <typename T>
class container2 : public container<T>{
public:
    virtual T func_x(){
        T temp;
        //do different stuff with list<T> test
        return temp;
    }
};

我想做的就是声明

container<T> x;
container2<T> y;

并且能够使y能够访问x的所有公共功能,除了它对于func_x的行为有所不同。

我现在遇到的问题是类container2中的func_x无法使用。

std::list<T> test;

我什至尝试将类容器完全公开。 仍然没有骰子。 能做到吗?

谢谢!

默认情况下,成员是private的:

template <typename T>
class container2 : public container<T>{
    //************
    // no modifier
    virtual T func_x(){
        T temp;
        //do different stuff with list<T> test
        return temp;
    }
private:
    std::list<T> test;
};

表示func_xprivate ,因为未指定修饰符。

您需要像对class container一样,显式地将func_x声明为public。

“仅仅是因为它在基类中是public ,并不意味着它对于派生类是自动的”。

编辑:

如果希望基类成员在派生类中可访问,则必须将它们声明为protectedpublic 因此,要回答您的后续问题,请更改

private:
    std::list<T> test;

protected:
    std::list<T> test;

另外,将来不要编辑问题来提出新的问题。 您应该创建一个新问题来处理新问题。 对于看到不再适用于新问题的答案的其他人来说,这可能会产生误导。

您需要在类声明中添加public:否则,所有声明的成员默认都是私有的。

template <typename T>
class container2 : public container<T>{
public: // <<==== ADD THIS
    virtual T func_x(){
        T temp;
        //do different stuff with list<T> test
        return temp;
    }
private:
    std::list<T> test;
};

问题在于您的func_x被派生对象隐藏了,因为您已将其重新定义为派生对象中的private

您需要将其公开。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM