构造函数与析构函数举例

代码:
#include <iostream> 
#include <cstring>
#include <stdio.h>
using namespace std;   
class Teacher 

     public: 
     Teacher() 
     { 
         director = new char[50]; 
         strcpy(director,"Myfuture"); 
     } 
     ~Teacher() 
     { 
         cout<<"free director memory in heap one time ."<<endl; 
         delete[] director; 
     } 
     char *show(); 
     void debug_show();
  
     protected: 
     char *director; 
}; 

void Teacher::debug_show()
{

 cout<<endl<<"director="<<director<<endl;
 cout<<"&director="<<&director<<endl;
 cout<<"*director="<<*director<<endl;
 cout<<"sizeof(director)="<<sizeof(director)<<endl;
 cout<<*(director)<<" "<<*(director+1)<<" "<<director[2]<<" "<<director[3]<<" "<<director[4]<<endl;
}

char *Teacher::show() 

    return director; 

class Student 

    public: 
    Student() 
    { 
        number = 1; 
        score = 100; 
    } 
    void show();   
    protected: 
    int number; 
    int score; 
    Teacher teacher;//这个类的成员teacher是用Teacher类进行创建并初始化的 
}; 
 
void Student::show() 

    cout<<teacher.show()<<endl<<number<<endl<<score<<endl; 

 
int main() 

     Student a; 
     Teacher debug;
     a.show(); 
     Student b[5]; 
     printf("sizeof(b)/sizeof(Student)=%d\n",sizeof(b)/sizeof(Student));
     for(int i=0; i<sizeof(b)/sizeof(Student); i++) 
     { 
         b[i].show(); 
     } 

     cout<<"sizeof(Student)="<<sizeof(Student)<<endl;
     cout<<"sizeof(Teacher)="<<sizeof(Teacher)<<endl;
           debug.debug_show();
}

Makefile:
all:
 g++ -o main tea_stu.cpp
 ./main
 

make:
[root@google Cpp]# make
g++ -o main tea_stu.cpp
./main
Myfuture
1
100
sizeof(b)/sizeof(Student)=5
Myfuture
1
100
Myfuture
1
100
Myfuture
1
100
Myfuture
1
100
Myfuture
1
100
sizeof(Student)=12
sizeof(Teacher)=4

director=Myfuture
&director=0xbfa3a668
*director=M
sizeof(director)=4
M y f u t
free director memory in heap one time .
free director memory in heap one time .
free director memory in heap one time .
free director memory in heap one time .
free director memory in heap one time .
free director memory in heap one time .
free director memory in heap one time .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值