avatar
m*o
1
请问这个继承最后输出的怎么是BB,而不是CC呢?main函数里的逻辑过程是什么样的?
#include
using namespace std;
class A{
protected:
virtual void print() { cout << "A" << endl; }
void print2() { cout << "AA" << endl; }
};
class B {
public:
virtual void print() { cout << "B" << endl; }
void print2() { cout << "BB" << endl; }
};
class C : public A, public B{
public:
void print2() { cout << "CC" << endl; }
};
int main()
{
C c;
B* p = &c;
p->print2();
};
avatar
c*g
2
print2 virtual?

【在 m*******o 的大作中提到】
: 请问这个继承最后输出的怎么是BB,而不是CC呢?main函数里的逻辑过程是什么样的?
: #include
: using namespace std;
: class A{
: protected:
: virtual void print() { cout << "A" << endl; }
: void print2() { cout << "AA" << endl; }
: };
: class B {
: public:

avatar
D*a
3
print2 is not virtual

【在 m*******o 的大作中提到】
: 请问这个继承最后输出的怎么是BB,而不是CC呢?main函数里的逻辑过程是什么样的?
: #include
: using namespace std;
: class A{
: protected:
: virtual void print() { cout << "A" << endl; }
: void print2() { cout << "AA" << endl; }
: };
: class B {
: public:

avatar
o*o
4
This is called upcast. You assigned the address of the object to
that of its base class. The function newly defined in derived class
will be un-accessible to that pointer. If a function defined virtual
in base class and you overrided it in derived class, the copy in
derived class will be called. Otherwise, the copy in base class is called.

【在 m*******o 的大作中提到】
: 请问这个继承最后输出的怎么是BB,而不是CC呢?main函数里的逻辑过程是什么样的?
: #include
: using namespace std;
: class A{
: protected:
: virtual void print() { cout << "A" << endl; }
: void print2() { cout << "AA" << endl; }
: };
: class B {
: public:

avatar
s*e
5
BB
avatar
s*e
6
Name lookup happens at compiling time.
Since the static type of p is B*, p will invoke the print2() defined in
its own scope unless print2() is virtual.
Obviously print2() is not virtual in this case and thus its own print2()
is called. ==> BB
avatar
S*X
7
正解,Thinking in C++好像专门有一章讲的很详细

【在 o*o 的大作中提到】
: This is called upcast. You assigned the address of the object to
: that of its base class. The function newly defined in derived class
: will be un-accessible to that pointer. If a function defined virtual
: in base class and you overrided it in derived class, the copy in
: derived class will be called. Otherwise, the copy in base class is called.

avatar
m*o
8
大概明白了,多谢各位!
avatar
m*o
9
那请教 B* p = &c; 是什么意思?
是定义一个类B的指针p, 其地址是&c, 那不还是用到了CLASS C吗???
avatar
t*l
10
upcast了

【在 m*******o 的大作中提到】
: 那请教 B* p = &c; 是什么意思?
: 是定义一个类B的指针p, 其地址是&c, 那不还是用到了CLASS C吗???

avatar
a*s
11
It seems that for the upcast, there is no need to use static_cast.
but for the downcast. it must.
B* p = &c; //ok
B* p = static_cast(&c) //ok
C* p = &b; //error
C* p = static_cast(&b) //ok
anyone explain it?

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