C++中memset一个对象

实验一

1、代码

#include <iostream>
#include <string.h>
using namespace std;
class A{
    public:
        A(int a1, int b1):a(a1),b(b1){
        
        }
        
        virtual ~A(){}
        virtual void print(){
            cout << "A: "<< a << " " << b << endl;
        }
        
                
        
        int a;
        int b;
};

class B:public A{
    public:
        virtual ~B(){}
        B(int a1, int b1):A(a1, b1){}
        virtual void print(){
            cout << "B: " << a << " " << b << endl;
        }

};


int main(){
    A a(1,2);
    a.print();
    cout << *((int*)&a) << endl;
    memset(&a, 0, sizeof(A));
    cout << a.a << " " << a.b << endl;
    a.print();
    cout << *((int*)&a) << endl;

    A *ap = new B(3, 4);
    ap->print();
    memset(ap, 0, sizeof(B));
    ap->print();
    delete ap;

}

 

2、结果

A: 1 2
102767936
0 0
A: 0 0
0
B: 3 4

 

3、分析

A a;是静态绑定,不会使用到虚函数指针。

A *a = new B(3, 4); 动态绑定,需要使用虚函数指针

实验二

1、代码

    A *ap = new A(5, 6);
    ap->print();
    memset(ap, 0, sizeof(A));
    ap->print();
    delete ap;

2、结果

A: 5 6
Segmentation fault (core dumped)

3、分析

A *a = new A(5, 6); 动态绑定,需要使用虚函数指针

 

静态联编==静态绑定:在编译期决定运行哪个函数

动态联编==动态绑定:在运行期决定运行哪个函数

 

posted on 2019-05-20 22:58  Shihu  阅读(505)  评论(0编辑  收藏  举报

导航