PHP 中 C++ 的虚函数的等价物是什么? [英] What's the equivalent of virtual functions of c++ in PHP?

查看:33
本文介绍了PHP 中 C++ 的虚函数的等价物是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抽象函数xxx吗?

我刚刚做了一个测试,似乎表明私有方法也是虚拟的?

I just made a test which seems to indicate a private method to be virtual too?

class a {
 private function test()
 {
  echo 1;
 }
}

class b extends a {
 private function test()
 {
  echo 2;
 }
 public function call()
 {
  $this->test();
 }
}

$instance = new b;
$instance->call();

输出为2

推荐答案

在 PHP 中,所有私有函数都不是虚拟的,因此无需显式声明它们为虚拟的.

In PHP all none private functions are virtual so there is no need to explicitly declare them as virtual.

将成员函数声明为 abstract 仅仅意味着基类不能提供实现,但所有派生类都应该提供.将方法定义为抽象与在 C++ 中执行以下操作相同

Declaring a member function as abstract simply means that the base class cannot provide an implementation but all deriving classes should. Defining the method as abstract is the same as doing the following in C++

virtual void foo() = 0;

这只是意味着派生类必须实现foo();

Which simply means that deriving classes must implement foo();

编辑:关于编辑的问题

b::call() 无法访问 a::test().由于这个原因,当调用私有函数时,只会调用调用它的类中的那个.

b::call() cannot access a::test(). For this reason when calling private functions only the one in the class where it was called from will be called.

编辑:关于评论:

(来自维基百科)

在面向对象的编程中,虚函数或虚方法是一个函数或方法,其行为可以在继承类中被具有相同签名的函数覆盖.

In object-oriented programming, a virtual function or virtual method is a function or method whose behaviour can be overridden within an inheriting class by a function with the same signature.

由于在 C++ 中明确说明您需要支付什么费用的想法,您必须将函数声明为虚拟函数以允许派生类覆盖函数.

Due to the idea of explicitly stating what you pay for in C++, you have to declare functions as being virtual to allow derived classes to override a function.

class Foo{
public:
    void baz(){
        std::cout << "Foo";
    }
};
class Bar : public Foo{
public:
    void baz(){
        std::cout << "Bar";
    }
};

int main(){
    Foo* f = new Bar();
    f->baz(); //baz is not virtual in Foo, so the output is Foo
}

将 baz 改为虚拟

class Foo{
public:
    virtual void baz(){
        std::cout << "Foo";
    }
};
//Same Bar declaration

int main(){
    Foo* f = new Bar();
    f->baz(); //baz is virtual in Foo, so the output is Bar as it will call the derived function
}

注意,如果上述示例中的变量 fBar*Bar 类型,那么 Foo::baz() 是否是虚拟的,因为预期的类型是已知的(程序员明确提供了它)

Note, if the variable f in the above sample was of type Bar* or Bar it wouldn't matter if Foo::baz() was virtual or not as the intended type is known (The programmer explicitly supplied it)

这篇关于PHP 中 C++ 的虚函数的等价物是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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