创建一个生物(biology)类。
1.构造函数没有返回值
2.构造函数与类型名一样
3、 可以有参数
4、构造函数可以重载
5.一个没有自定义的构造函数,则c++编译器会自动生成一个默认的,共有的,无参的构造函数。 (定义了就不会在生成默认的构造函数)
类的常量成员引用只能用类的初始化列表来初始化,不能用类的构造函数进行初始化
man.cpp
#include <iostream>
#include "biology.h"
//#include "food.h"
using namespace std;
int main()
{
biology t_biology1;
t_biology1.print();
cout <<endl;
//有参构造函数
biology t_biology2("tree",2000,300,"meat",3);
cout <<endl;
t_biology2.print();
cout << "Hello World!" << endl;
return 0;
}
biology.h
#ifndef BIOLOGY_H #define BIOLOGY_H #include <iostream> #include <string.h> #include "food.h" using namespace std; class biology { public: //构造函数声明 biology(); /* 默认构造函数 */ //有参构造函数 biology(const string &t_name, int t_weight,int t_height,const string &t_foodName,int t_foodTime); void print() { cout <<"biology name:" << m_name <<endl; cout <<"biology weight:" << m_weight <<endl; cout <<"biology height:" << m_height <<endl; cout <<"biology number:" << m_number <<endl; m_food.print(); } private: string m_name; int m_weight; int m_height; food m_food;//类的组合 const int m_number; //c++ 2011 支持 }; #endif // BIOLOGY_H
biolog.cpp
#include "biology.h" //构造函数的实现 biology::biology():m_number(200) { cout << "biology()"<<endl; m_name="tiger"; m_weight=110; m_height=65; } //有参数构造函数 //用初始化列表来初始化成员变量 biology::biology(const string &t_name, int t_weight,int t_height,const string &t_foodName,int t_foodTime) :m_name(t_name),m_weight(t_weight),m_height(t_height),m_number(2000), m_food(t_foodName,t_foodTime) { cout << "biology(……………………)"<<endl; // m_name=t_name; // m_weight=t_weight; // m_height=t_height; }
food.h
#ifndef FOOD_H #define FOOD_H #include <iostream> #include <string> using namespace std; class food { public: food(); food(const string &t_name,int t_validTime); void print(); private: string m_name; int m_validTime; //食物有效期 }; #endif // FOOD_H
--
food.cpp
#include "food.h" food::food() { cout <<"food()" <<endl; m_name="fish"; m_validTime=1; } food::food(const string &t_name, int t_validTime) :m_name(t_name),m_validTime(t_validTime) { cout <<"foo(…………)"<<endl; } void food::print() { cout <<"food name: "<<m_name+"\t\t"<< "food validTime: "<<m_validTime <<endl; }
运行如图