#C++:构造函数与析构函数应用示例
##declare.h声明文件
#include <string>
using namespace std;
class Eat
{
private:
string name_; //类成员最好用_后缀,防止与成员函数的参数一致
string thing_to_eat_;
int weight_;
public:
Eat(); //默认构造函数
Eat(const string &name,const string &thing_to_eat,int weight); //构造函数,带输入参数
~Eat(); //析构函数,如果没写,编译器会自动分配
void move();
void show_weight();
};
##implementation.cpp
#include "declare.h"
#include <iostream>
using namespace std;
Eat::Eat()
{
cout<<"initial default constructor"<<endl;
name_="Vitus";
thing_to_eat_="shit";
weight_=130;
}
Eat::Eat(const string &name,const string &thing_to_eat,int weight)
{
cout<<"initial constructor"<<endl;
name_=name;
thing_to_eat_=thing_to_eat;
weight_=weight;
}
Eat::~Eat()
{
cout<<"destractor is called"<<endl;
}
void Eat::move()
{
cout<<"the subject: "<<name_<<" eat: "<<thing_to_eat_<<endl;
}
void Eat::show_weight()
{
cout<<"the subject: "<<name_<<" is weight: "<<weight_<<endl;
}
##Eat.cpp
#include <iostream>
#include <string>
#include "declare.h"
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv) {
using namespace std;
Eat person1;
Eat person2("Toria","shit",120);
person1.move();
person1.show_weight();
person2.move();
person2.show_weight();
return 0;
}
##注意点:
1.构造函数和析构函数没有返回类型(类名::构造函数/析构函数)
2.其他成员函数记得写上类名(返回类型 类名::成员函数名(参数))
3.成员名称记得加“_”后缀以便和构造函数的参数重名
4.调用构造函数为 (类名 构造函数名) 不要带括号!!!,会误以为是返回类型为此类的函数
5.“const”???不知道为啥?。。