代码:
#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 .