bod*_*ydo -4 php c++ oop inheritance private
我写了这个简单的例子来说明我的问题.我有一个Base类和Derived类.当我调用派生类的justdoit函数时,它不调用派生类doer函数,而是调用基类的doer函数.
预期产量:
Base::doer
Derived::doer
Run Code Online (Sandbox Code Playgroud)
实际产量:
Base::doer
Base::doer
Run Code Online (Sandbox Code Playgroud)
码:
<?
class Base {
public function justdoit() {
$this->doer();
}
private function doer() {
print "Base::doer\n";
}
}
class Derived extends Base {
private function doer() {
print "Derived::doer\n";
}
}
$b = new Base;
$b->justdoit();
$d = new Derived;
$d->justdoit();
?>
Run Code Online (Sandbox Code Playgroud)
这是C++中的相同代码示例,它可以工作:
class A {
public:
void justdoit();
private:
virtual void doit();
};
void A::justdoit() {
doit();
}
void A::doit() {
std::cout << "A::doit\n";
}
class B : public A {
private:
virtual void doit();
};
void B::doit() {
std::cout << "B::doit\n";
}
int main() {
A a;
B b;
a.justdoit();
b.justdoit();
}
Run Code Online (Sandbox Code Playgroud)
输出:
A::doit
B::doit
Run Code Online (Sandbox Code Playgroud)
有趣的是,如果我改变了原来的PHP例子和替换private function用protected function它开始工作:
<?
class Base {
public function justdoit() {
$this->doer();
}
protected function doer() {
print "Base::doer\n";
}
}
class Derived extends Base {
protected function doer() {
print "Derived::doer\n";
}
}
$b = new Base;
$b->justdoit();
$d = new Derived;
$d->justdoit();
?>
Run Code Online (Sandbox Code Playgroud)
输出:
Base::doer
Derived::doer
Run Code Online (Sandbox Code Playgroud)
有谁知道为什么PHP和C++产生不同的结果?为什么改变private以protected在PHP使它产生相同的结果为C++?
请参阅public,private和protected之间的区别是什么?有关PHP中的public,protected和private的讨论.
这是我的看法:
该函数justdoit在Base类中声明.当doer被声明private在Derived类,它具有外部不可见Derived类,甚至没有给Base类.因此,即使justdoit在实例上Derived执行,它也会执行doerin,Base因为这是唯一doer可见的函数.