75 lines
1.3 KiB
C++
75 lines
1.3 KiB
C++
|
// 对象的构造与析构
|
||
|
#include <iostream>
|
||
|
#include <cstdlib>
|
||
|
#include <cstring>
|
||
|
|
||
|
using namespace std;
|
||
|
|
||
|
class Animal
|
||
|
{
|
||
|
public:
|
||
|
Animal();
|
||
|
Animal(const char *name, const char *food);
|
||
|
~Animal(); // 析构函数(对象回收时,清理资源)
|
||
|
|
||
|
public:
|
||
|
void eat();
|
||
|
void say(const char *msg);
|
||
|
|
||
|
private:
|
||
|
char *name, *food;
|
||
|
};
|
||
|
|
||
|
Animal::Animal()
|
||
|
{
|
||
|
name = (char *)malloc(32);
|
||
|
food = (char *)malloc(32);
|
||
|
strcpy(name, "小动物");
|
||
|
strcpy(food, "水");
|
||
|
}
|
||
|
|
||
|
Animal::Animal(const char *name, const char *food)
|
||
|
{
|
||
|
this->name = (char *)malloc(32);
|
||
|
this->food = (char *)malloc(32);
|
||
|
strcpy(this->name, name);
|
||
|
strcpy(this->food, food);
|
||
|
}
|
||
|
|
||
|
Animal::~Animal()
|
||
|
{
|
||
|
cout << name << "空间回收" << endl;
|
||
|
|
||
|
// 回收在构造函数(初始化)中动态分配的空间
|
||
|
free(name);
|
||
|
free(food);
|
||
|
}
|
||
|
|
||
|
void Animal::eat()
|
||
|
{
|
||
|
cout << name << "吃: " << food << endl;
|
||
|
}
|
||
|
|
||
|
void Animal::say(const char *msg)
|
||
|
{
|
||
|
cout << name << "遇到主人: " << msg << endl;
|
||
|
}
|
||
|
|
||
|
int main()
|
||
|
{
|
||
|
// 尽量使用堆空间创建类的对象: 使用 类指针 和 new 关键字
|
||
|
Animal *anm1 = new Animal();
|
||
|
anm1->eat();
|
||
|
|
||
|
// 使用栈空间的情况
|
||
|
Animal anm2;
|
||
|
anm2.say("小浣熊");
|
||
|
|
||
|
// 使用括号
|
||
|
Animal anm3("小黄", "肉");
|
||
|
anm3.eat();
|
||
|
anm3.say("旺旺...");
|
||
|
|
||
|
return 0;
|
||
|
}
|