avatar
h*o
1
1. 现在有AB两个类,由于AB的constructor比较大,又只有f()不相同
我想在初始化B的时候实现动态绑定,请问怎么样可以实现?不成功的代码如下
#include
using namespace std;
class A{
public:
A() { f(); }
virtual void f() { cout << "As class A" << endl; }
};
class B: public A{
public:
B():A() { }
virtual void f() { cout << "As class B" << endl; }
};
int main()
{
B b;
return 0;
}
输出结果为As class A
2. 这个我不太清楚是不是compiler的问题还是什么特别规则,感觉非常奇怪
#include
using namespace std;
class A{
public:
virtual void f() { cout << "As class A" << end
avatar
t*t
2
constructor or destructor can call virtual member functions, but the version
they called is the one defined in its own class (i.e. will not be overrided
). in other words, you can't do dynamic binding in ctor/dtor.
if you really have to, do a delayed initialization in a separate member (e.g
. init())

【在 h**o 的大作中提到】
: 1. 现在有AB两个类,由于AB的constructor比较大,又只有f()不相同
: 我想在初始化B的时候实现动态绑定,请问怎么样可以实现?不成功的代码如下
: #include
: using namespace std;
: class A{
: public:
: A() { f(); }
: virtual void f() { cout << "As class A" << endl; }
: };
: class B: public A{

avatar
t*t
3
for the 2nd situation, isn't that exactly what dynamic-binding means?

【在 h**o 的大作中提到】
: 1. 现在有AB两个类,由于AB的constructor比较大,又只有f()不相同
: 我想在初始化B的时候实现动态绑定,请问怎么样可以实现?不成功的代码如下
: #include
: using namespace std;
: class A{
: public:
: A() { f(); }
: virtual void f() { cout << "As class A" << endl; }
: };
: class B: public A{

avatar
h*o
4
even if the second f() is private?

【在 t****t 的大作中提到】
: for the 2nd situation, isn't that exactly what dynamic-binding means?
avatar
h*o
5
i tried. it doens't work either if i let the ctor call init().

version
overrided
.g

【在 t****t 的大作中提到】
: constructor or destructor can call virtual member functions, but the version
: they called is the one defined in its own class (i.e. will not be overrided
: ). in other words, you can't do dynamic binding in ctor/dtor.
: if you really have to, do a delayed initialization in a separate member (e.g
: . init())

avatar
t*t
6
no, i meant DELAYED initialization. you have to call init() (manually) after
the object is initialized.

【在 h**o 的大作中提到】
: i tried. it doens't work either if i let the ctor call init().
:
: version
: overrided
: .g

avatar
t*t
7
oh, didn't notice the private. Access control is checked statically, so if
you call a->f(), it will check A::f(). it doesn't matter any private member
overrides it later.

【在 h**o 的大作中提到】
: even if the second f() is private?
avatar
h*o
8
i see. many many thanks!

member

【在 t****t 的大作中提到】
: oh, didn't notice the private. Access control is checked statically, so if
: you call a->f(), it will check A::f(). it doesn't matter any private member
: overrides it later.

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。