虚拟函数...为什么这是私有的?
我正在尝试使以下代码起作用...
#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;
我什至尝试过将类容器完全公开。还是没有骰子。这可以做到吗?
谢谢!
I'm trying to make the following bit of code to work...
#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;
}
};
What I want to be able to do is declare
container<T> x;
container2<T> y;
And be able to have y have access to all the public functions of x, except that it behaves differently for func_x.
The problem I have now is that func_x in class container2 cannot use;
std::list<T> test;
I have even tried making class container completely public. Still no dice. Can this be done?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
默认情况下,类的成员是
private
:意味着
func_x
是private
,因为没有指定修饰符。您需要将
func_x
显式声明为 public,就像您对class 容器
所做的那样。“仅仅因为它在基类中是
public
并不意味着它对于派生类来说自动也是这样”。编辑:
如果您希望在派生类中可以访问基类成员,则必须将它们声明为
protected
或public
。因此,要回答您的后续问题,请更改为
“此外,将来不要编辑问题来提出新问题”。您应该创建一个新问题来处理新问题。对于看到不再适用于新问题的答案的其他人来说,这可能会产生误导。
Members are by default
private
for classes:means that
func_x
isprivate
, since no modifier is specified.You need to explicitly declare
func_x
as public, as you have forclass container
."Just because it's
public
in the base class doesn't mean it's automatically that way for the derived".EDIT:
If you want base class members to be accessible in derived classes, you must declare them either
protected
orpublic
. So, to answer your follow-up question, changeto
Also, in the future, don't edit the question to ask a new one. You should create a new question to deal with the new issue. It can be misleading for others who see answers that no longer apply to the new question.
您需要将
public:
添加到您的类声明中:否则,默认情况下声明的所有成员都是私有的。You need to add
public:
to your class declaration: otherwise, all members declared are private by default.问题是您的 func_x 被派生对象隐藏,因为您已将其重新定义为派生对象中的
private
。你需要将其公开。
The problem is that your
func_x
is hidden by your derived object, because you've redefined it, asprivate
in derived.You need to make it public.