C++构造函数1

创建一个生物(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;


}


运行如图




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

仰望星空e

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值