由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
Programming版 - private destructor
相关主题
问个虚函数的作用Two questions on virtual destructor
namespace defined in another file最初级的白痴C++问题
A try-catch problem in C++how do I reseat a reference?
一个C++语法问题question about c++ constructor
请问这个C++程序有什么问题吗What is wrong with the constructor calling?
请教一个基本的constructor和destrcutor问题请教这个程序里用到了什么constructor啊?有几个copy constructor?
question for C++ constant菜鸟请教smart pointer
C++ 的 问题【C++】请问这样有没有memory leak?多谢
相关话题的讨论汇总
话题: destructor话题: private话题: public话题: endl话题: cout
进入Programming版参与讨论
1 (共1页)
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(){

1 (共1页)
进入Programming版参与讨论
相关主题
【C++】请问这样有没有memory leak?多谢请问这个C++程序有什么问题吗
g++-2.95 -> g++-3.3/3.4请教一个基本的constructor和destrcutor问题
c++ class definitionquestion for C++ constant
问一个for循环的问题C++ 的 问题
问个虚函数的作用Two questions on virtual destructor
namespace defined in another file最初级的白痴C++问题
A try-catch problem in C++how do I reseat a reference?
一个C++语法问题question about c++ constructor
相关话题的讨论汇总
话题: destructor话题: private话题: public话题: endl话题: cout