C++ 一个类可以有虚拟数据成员吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3698831/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
can a class have virtual data members?
提问by vandanak
class Base{
public:
void counter();
....
}
class Dervied: public Base{
public:
....
}
void main()
{
Base *ptr=new Derived;
ptr->counter();
}
To identify that the base class pointer is pointing to derived class and using a derived member function, we make use of "virtual".
为了识别基类指针指向派生类并使用派生成员函数,我们使用“虚拟”。
Similarly, can we make derived data members "virtual"? (the data member is public)
同样,我们可以使派生数据成员“虚拟”吗?(数据成员是公开的)
回答by liaK
virtual
is a Function specifier...
virtual
是函数说明符...
From standard docs,
从标准文档,
7.1.2 Function specifiers
Function-specifiers can be used only in function declarations.
function-specifier:
inline
virtual
explicit
So there is nothing called Virtual data member.
所以没有什么叫做Virtual data member。
Hope it helps...
希望能帮助到你...
回答by mmonem
No, but you can create a virtual function to return a pointer to what you call virtual data member
不,但您可以创建一个虚拟函数来返回一个指向您所谓的虚拟数据成员的指针
回答by Naveen
No, in C++ there are no virtual data members.
不,在 C++ 中没有虚拟数据成员。
回答by Chubsdad
To identify that the base class pointer is pointing to derived class and using a derived member function, we make use of "virtual".
为了识别基类指针指向派生类并使用派生成员函数,我们使用“虚拟”。
That is not correct. We make virtual functions to allow derived classes to provide different implementation from what the base provides. It is not used to identify that the base class pointer is pointing to derived class.
那是不正确的。我们创建虚函数以允许派生类提供与基类提供的不同的实现。它不用于标识基类指针指向派生类。
Similarly, can we make derived data members "virtual"? (the data member is public)
同样,我们可以使派生数据成员“虚拟”吗?(数据成员是公开的)
Only non static member functions can be virtual. Data members can not be.
只有非静态成员函数可以是虚拟的。数据成员不能。
Here'sa link with some more info on that
这是一个包含更多信息的链接
回答by Ronny Brendel
I think not, but you might simulate it using virtual getters and setter perhaps?
我认为不是,但您可能会使用虚拟 getter 和 setter 来模拟它?
回答by Igor Zevaka
No, because that would break encapsulation in a myriad of unexpected ways. Whatever you want to achieve can be done with protected attributes and/or virtual functions.
不,因为那会以无数意想不到的方式破坏封装。无论您想要实现什么,都可以使用受保护的属性和/或虚拟函数来完成。
Besides, virtual functions are a method of dispatch(i.e. selecting which function is going to be called), rather than selecting a memory location corresponding to the member attribute.
此外,虚函数是一种调度方法(即选择要调用哪个函数),而不是选择成员属性对应的内存位置。
回答by Mauro
Maybe you can see the problem in a equivalent way:
也许您可以以等效的方式看到问题:
class VirtualDataMember{
public:
...
}
class DerviedDataMember: public VirtualDataMember{
public:
...
}
class Base{
public:
VirtualDataMember* dataMember;
void counter();
...
}