v****s 发帖数: 1112 | 1 this program can compile and run.
return value:
-858993460
大侠给解释下c++语法为何会允许这种polymorphism? 这个返回值是怎么决定出来的?
#include
using namespace std;
class clsBase {
public:
char value;
};
class clsA : public clsBase {
public:
void * link;
};
class clsB : public clsBase {
};
int main(){
clsBase *pbase;
clsA a;
int i = 1077;
a.link = (void *)i;
clsB b;
pbase = & b;
cout<< (int)((clsA *)pbase)->link << endl;
getchar();
} | a****o 发帖数: 686 | 2 首先,这个问题和polymorphism没有任何关系。
其次,你这个向下cast,是强制类型转换,结果是undefined。
再次,i从指针型,转化为整型,再转化,意图何在?
综述,你这问题就是一砣一砣的强制转化。根本就没有polymorphism的事。 | k******r 发帖数: 2300 | 3 First of all, in c++, we don't use c-style casting. We use static_cast,
dynamic_cast or reinterpret_cast in c++. In order to answer your question,
we need to explain it from static_cast and dynamic_cast separately(I put
reinterpret_cast aside because probably it is not your interest at this time
).
If you apply static_cast on a clsBase pointer to convert it to a clsA
pointer , since clsBase is base class of clsA, so it is perfectly legal. In
this case, there is not polymorphism involved. On the other hand, if you
apply dynamic_cast on a pbase to convert it to a clsA pointer, it will fail
because run time type of pbase at this time is of clsB*. This time
polymorphism does come into play.
Hopefully it helps.
【在 v****s 的大作中提到】 : this program can compile and run. : return value: : -858993460 : 大侠给解释下c++语法为何会允许这种polymorphism? 这个返回值是怎么决定出来的? : #include : using namespace std; : class clsBase { : public: : char value; : };
|
|