虚拟私有成员函数 [英] Virtual private member functions

查看:100
本文介绍了虚拟私有成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我们需要虚拟私人会员功能?为什么它不是一个

(编译时)错误?

Why we need "virtual private member functions"? Why it is not an
(compile time) error?

推荐答案

3月28日,12:下午50点,v4vijayakumar < vijayakumar.subbu ... @ gmail.com>

写道:
On Mar 28, 12:50 pm, "v4vijayakumar" <vijayakumar.subbu...@gmail.com>
wrote:

为什么我们需要虚拟私人会员功能?为什么它不是一个

(编译时)错误?
Why we need "virtual private member functions"? Why it is not an
(compile time) error?



但为什么它应该是编译时错误?

But why it should be a compile time error?


3月28日,12日:上午50点,v4vijayakumar < vijayakumar.subbu ... @ gmail.com>

写道:
On Mar 28, 12:50 am, "v4vijayakumar" <vijayakumar.subbu...@gmail.com>
wrote:

为什么我们需要虚拟私人会员功能?为什么它不是一个

(编译时)错误?
Why we need "virtual private member functions"? Why it is not an
(compile time) error?



为什么它应该是编译时错误?私有与

可访问性有关 - 与虚拟是否完全无关。

什么阻止公共成员函数调用虚拟

私人会员功能?


非虚拟功能是可访问的接口和私人

虚拟功能是隐藏的工蜂。

Why should it be a compile time error? Private has to do with
accessibility - completely unrelated to whether its virtual or not.
What is preventing a public member function from calling a virtual
private member function?

Consider NVI (non-virtual interface) Idiom which does exactly that.
The non-virtual function is the accessible interface and the private
virtual function is the hidden worker-bee.


3月28日06:50,v4vijayakumar < vijayakumar.subbu ... @ gmail.com>

写道:
On 28 Mar, 06:50, "v4vijayakumar" <vijayakumar.subbu...@gmail.com>
wrote:

为什么我们需要虚拟私人会员功能?
Why we need "virtual private member functions"?



因为它允许你扩展类而不用担心你改变界面。例如,您可以在base-

类中提供检查,以便某些不变量始终为真,并且这不能通过继承来绕过。


类基础

{

虚拟int doFoo(int)= 0;


public:

int foo(int);

};


int Base :: foo(int n)

{

//检查n

int tmp = doFoo(n);

//检查tmp

返回tmp;

}


类派生:公共基础

{

虚拟int doFoo(int);

};


所以在这里我们让派生类提供所有功能(你好b / b
)当然在Base中做了一些默认的实现)但总是

检查传递给doFoo()并从doFoo()返回的值我们可以做一些保证




-

Erik Wikstr?m

Because it allows you to extend classes without being afraid that you
change the interface. You could for example provide checks in the base-
class so that some invariants always are true and this can''t be
circumvented by inheritance.

class Base
{
virtual int doFoo(int) = 0;

public:
int foo(int);
};

int Base::foo(int n)
{
// do checks on n
int tmp = doFoo(n);
// Check tmp
return tmp;
}

class Derived : public Base
{
virtual int doFoo(int);
};

So here we let the derived class provide all the functionality (you
cold of course make some default implementation in Base) but by always
checking the values passes to and returned from doFoo() we can make
some guarantees.

--
Erik Wikstr?m


这篇关于虚拟私有成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆