为什么派生类的函数在 PHP 中没有通过 base 调用?
Why doesn't derived class's function get called through base in PHP?
我写了一个简单的例子来演示我的问题。我有一个基类和派生类。当我调用派生类的justdoit
函数时,它不调用派生类doer
函数,而是调用基类的doer
函数。
预期输出:
Base::doer
Derived::doer
实际输出:
Base::doer
Base::doer
代码:
<?
class Base {
public function justdoit() {
$this->doer();
}
private function doer() {
print "Base::doern";
}
}
class Derived extends Base {
private function doer() {
print "Derived::doern";
}
}
$b = new Base;
$b->justdoit();
$d = new Derived;
$d->justdoit();
?>
以下是C++中的相同代码示例,它可以工作:
class A {
public:
void justdoit();
private:
virtual void doit();
};
void A::justdoit() {
doit();
}
void A::doit() {
std::cout << "A::doitn";
}
class B : public A {
private:
virtual void doit();
};
void B::doit() {
std::cout << "B::doitn";
}
int main() {
A a;
B b;
a.justdoit();
b.justdoit();
}
输出:
A::doit
B::doit
有趣的是,如果我改变我原来的PHP示例,用protected function
替换private function
,它就会开始工作:
<?
class Base {
public function justdoit() {
$this->doer();
}
protected function doer() {
print "Base::doern";
}
}
class Derived extends Base {
protected function doer() {
print "Derived::doern";
}
}
$b = new Base;
$b->justdoit();
$d = new Derived;
$d->justdoit();
?>
输出:
Base::doer
Derived::doer
有人知道为什么PHP和C++会产生不同的结果吗?为什么在PHP中将private
更改为protected
会产生与C++相同的结果?
查看公共、私有和受保护之间的区别是什么?以便在PHP中很好地讨论公共、受保护和私有。
这是我的看法:
函数justdoit
是在Base
类中声明的。当doer
在Derived
类中声明为private
时,它在Derived
类之外没有可见性,甚至对Base
类也没有可见性。因此,即使在Derived
的实例上执行justdoit
,它也会在Base
中执行doer
,因为这是它唯一可见的doer
函数
private
方法只能被该类访问。protected
方法可以由子类访问。通过声明private function doer
,您明确表示只有类的实例才能调用该函数。
类似问题
"那么它在C++中是如何工作的呢?">
在您的C++代码中,您正在调用该函数的派生版本。
$d = new Derived;
$d->justdoit();
这段代码将调用C++中"justdoit(("的派生版本,而不是基函数。当我们创建虚拟函数时,会创建一个vtable,用于维护和保存被覆盖函数的地址。在调用时,根据要调用的对象的类型,会调用函数。这里,
$b = new Base;
$b->justdoit();
在这个块中,您使用的是基本对象,因此调用了基本版本。
我希望你的问题得到答复。
- 构造函数采用 Base&不被调用
- 从 Base 引用对象调用派生类的成员
- 如何在派生类中不显式调用base::func()的情况下从基类执行虚拟函数
- 派生对象调用的 Base 方法的模板推导
- 使用 static_cast、dynamic_cast 或显式转换进行派生指向 Base 指针转换的指针不会调用 base 函数
- 我如何调用基类的虚拟函数定义,这些定义在Ampract Base类和C 中的派生类中都有定义
- 为什么当派生类调用 base 的纯虚函数时 g++ 不抱怨?
- 在不手动键入base::method()的情况下,我可以递归地调用每个基中的方法吗
- 正在调用派生方法而不是Base
- 让 foo(derived_object) 调用 foo(Base const&) 而不是模板函数?
- 这是正确的吗:在构造 Base 对象之前调用了派生的虚拟方法
- 调用 ~Derived() 和 ~Base() 之间的对象状态
- C++错误,显示创建链接列表调用"error LinkedList Interface is an inaccessable base of linkedlist"
- 如何在创建新的 obj() 时调用基类构造函数 new base(argT argV)
- 从 base 的特定派生类型调用特定函数
- 使用 "new" 为派生类分配内存时,如何调用 Base 构造函数?
- 在Python中继承c++的Base,使用SWIG调用抽象方法
- 为什么派生类的函数在 PHP 中没有通过 base 调用?
- C++:从派生实例调用 base 中的纯虚拟方法重载
- 多重继承派生类:如何在不重复调用 base 的情况下重用派生函数