Upcating(向上造型)

来源:互联网 发布:linux shell 当前目录 编辑:程序博客网 时间:2024/06/02 16:10

Upcating is the act of converting from a derived reference or pointer to a base class reference or pointer

可以将子对象的指针转换成父对象的指针

Tips

  • 对象的 size 就是对象的成员变量的size总和(不考虑内存对齐)
  • 对象的方法不占用对象的内存空间
  • 子对象的指针转换成父对象指针后
    • 子对象新增的成员变量相当于被截断
    • 不能通过指向父对象的指针调用子对象的方法

eg,

#include <iostream>using namespace std;class A {public:    A():i(19){}    void print(){cout << "A.i = " << i << endl;}private:    const int i;};class B : public A{public:    B():j(99){}    ~B(){}    void print() {cout << "B.j = " << j << endl;}    void f() {cout << "I'm f()" << endl;}private:    int j;};int main(int argc, char const *argv[]){    A a;    a.print();    cout << "size of A is " << sizeof(A) << endl;//4    B b;    b.print();    cout << "size of B is " << sizeof(B) << endl;//8    int *c = (int *)&a;//通过指针c修改了const int i    *c = 89;    a.print();//A.i = 89    A* p = &b;    p->print();//A.i = 19. 调的A的print    //p->f();//Error,不能通过指向父对象的指针调用子对象的方法    return 0;}

然而, 下面的程序似乎不能修改const int

#include <iostream>using namespace std;int main(void){    const int a = 10;    cout << "a = " << a << endl; //10    cout << "where's a    : " << &a << endl;    int *p = (int *)&a;    *p = 20;    cout << "a = " << a << endl; //10    cout << "*p = " << *p << endl; //20    cout << "where's p    : " << &p << endl;    printf("where's main : %p\n", main);    return 0;}

输出:

a = 10
where’s a : 0x7fff52dd0c58
a = 10
where’s p : 0x7fff52dd0c50
where’s main : 0x10ce2fea0

从上面的结果可以看出,a 确实有被修改成 20,因为存放 a 这块内存的值通过p可以看出来。但为什么 a 的值打印出来还是10呢?

[答案]:编译器发现这是 const,就不重新从存放a的地址处拿值了。

♠ 可以用volatile告诉编译器,每次取a都要重新拿值,如下所示:

const volatile int a = 10;

这样,a 的值打印出来也是20了。可见,即使一个变量声明为const,还是可能通过其他变量(指针)进行修改的。

0 0
原创粉丝点击