r*******y 发帖数: 1081 | 1 Look at this example:
#include
using namespace std;
class A{
public:
virtual ~A(){cout <<"A"<
};
class B:public A{
~B(){cout <<"B" <
};
int main(){
A * pa = new B;
delete pa;
}
the output is
B
A
~B() is called because of the polymorphism. My question is that why
a private destructor ~B() can be called here?
Thanks |
m*****e 发帖数: 4193 | 2 My guess is that private/public protection is effective only at compile time
, but virtual functions are run-time bound. So the code compiles, because
you are invoking the destructor through A's public destructor. But at run-
time it's actually B's destructor that gets invoked.
【在 r*******y 的大作中提到】 : Look at this example: : #include : using namespace std; : class A{ : public: : virtual ~A(){cout <<"A"<: }; : class B:public A{ : ~B(){cout <<"B" <: };
|
B*M 发帖数: 1340 | 3 是的,
class A{
public:
virtual void f(){
cout << "A's f" << endl;
}
};
class B: public A{
private:
void f(){
cout << "B's f" << endl;
}
};
int main(){
A* a = new B();
a->f();
delete a;
}
这段代码输出的是: B's f
public private的约束是在编译时候检查的,运行时就不管了,
time
【在 m*****e 的大作中提到】 : My guess is that private/public protection is effective only at compile time : , but virtual functions are run-time bound. So the code compiles, because : you are invoking the destructor through A's public destructor. But at run- : time it's actually B's destructor that gets invoked.
|
X****r 发帖数: 3557 | 4 Yes, C++ 98 11.6
1. The access rules for a virtual function are determined by
its declaration and are not affected by the rules for a
function that later overrides it.
【在 B*M 的大作中提到】 : 是的, : class A{ : public: : virtual void f(){ : cout << "A's f" << endl; : } : }; : class B: public A{ : private: : void f(){
|