h**o 发帖数: 347 | 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 |
t****t 发帖数: 6806 | 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{
|
t****t 发帖数: 6806 | 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{
|
h**o 发帖数: 347 | 4 even if the second f() is private?
【在 t****t 的大作中提到】 : for the 2nd situation, isn't that exactly what dynamic-binding means?
|
h**o 发帖数: 347 | 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())
|
t****t 发帖数: 6806 | 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
|
t****t 发帖数: 6806 | 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?
|
h**o 发帖数: 347 | 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.
|