//新建如图文件
//在头文件.h中声明,在.cpp中实现
//main.cpp代码如下
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include "test.h"
#include <string.h>
using namespace std; int main()
{
//Student st ;//栈上,这个类的构造函数在类被定义为变量的时候,自动调用
Student *p = new Student("mike",);//在堆上创建实例,不管在堆上,还是在栈里面,只要这个类成了一个对象,构造函数都会自动被调用(带参的函数)。
p->show();
//p->add();//父类中是private
/*strcpy(p->name, "tom");
p->age = 10;*/
//p->set_money(500);
cout << "name = " << p->name << ",age = " << p->age<<endl;
cout << "money = " << p->get_money()<<endl;
delete p;//自动调用析构函数
system("pause");
return ;
}
//person.cpp代码
#include "person.h"
#include <stdio.h> Person::Person()
{ } void Person::show()
{
printf("show\n");
} void Person::add()
{
printf("add\n");
}
//test.cpp
#define _CRT_SECURE_NO_WARNINGS
#include "test.h"
#include <stdio.h>
#include <string.h> void Student::set_money(int n)
{
money = n;
}
int Student::get_money()
{
return money;
} Student::Student(const char *_name, int _age, int _money)
{
strcpy(name, _name);//this
age = _age;
money = _money;
}
Student::Student()
{
memset(name, , sizeof(name));
age = ;
money = ;
printf("hello world!\n");
//classes = new char[100];//在构造函数中分配了100个char。
}
Student::~Student()
{
printf("调用了析构函数。\n");
//delete[]classes;//清理构造函数分配的堆空间内存。
}
//person.h
#ifndef PERSON_H
#define PERSON_H class Person
{
private:
void add();
public:
Person();
void show();
};
#endif // !PERSON_H
//test.h
#ifndef TEST_H
#define TEST_H #include "person.h" class Student : public Person
{
public:
char name[];
char *classes;
int age;
private:
int money;
public:
void set_money(int n);
int get_money();
Student(const char *_name, int _age,int money = );//构造函数重载
Student();
~Student();
}; #endif
//运行结果