m*******o 发帖数: 264 | 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();
}; |
c***g 发帖数: 472 | 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:
|
D*******a 发帖数: 3688 | 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:
|
o*o 发帖数: 404 | 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:
|
s*******e 发帖数: 28 | |
s*******e 发帖数: 28 | 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 |
S****X 发帖数: 507 | 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.
|
m*******o 发帖数: 264 | |
m*******o 发帖数: 264 | 9 那请教 B* p = &c; 是什么意思?
是定义一个类B的指针p, 其地址是&c, 那不还是用到了CLASS C吗??? |
t*****l 发帖数: 121 | 10 upcast了
【在 m*******o 的大作中提到】 : 那请教 B* p = &c; 是什么意思? : 是定义一个类B的指针p, 其地址是&c, 那不还是用到了CLASS C吗???
|
a*******s 发帖数: 324 | 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了
|