c++ 类初始化列表,构造函数,复制构造函数

//
// Created by darren on 17-9-30.
//
#ifndef TEST_1_CLASS_TEST_H
#define TEST_1_CLASS_TEST_H

#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <errno.h>
#include <stdio.h>
using namespace std;
class Human{
public:
    Human(char *name, char* &gender, int lWeight);
    Human(Human &am);
    int eat();
    int run();
    void setAttribute(int age, int heighe);    //attribute
    inline void printf(){
        cout<<"height"<<height<<endl;
        cout<<"age:"<<age<<endl;
        cout<<"weight:"<<weight<<endl;
        cout<<"gender:"<<gender<<endl;
        cout<<"myName:"<<myName<<endl;
    }
    ~Human();

private:
    int height;
    int age;
    char* myName;
    char* &gender;
    const int weight;
public:
    static int iNumber;        //在类外对static类型的数据成员进行初始化
};



#endif //TEST_1_CLASS_TEST_H

//
// Created by darren on 17-9-30.
//

#include "1_class_test.h"

using namespace std;

int Human::iNumber =0;
int Human::eat() {
    cout << "we eat the food" << endl;
    return 0;
}

int  Human::run() {
    cout << "we running" << endl;
}

void Human::setAttribute(int sAge, int sHeighe) {

    age = sAge;
    height = sHeighe;
}

Human::Human(char *name, char *&lGender, int lWeight = 0) : gender(lGender), weight(lWeight) {

    iNumber++;
    cout << "name:" << name << "lGender:" << lGender << "lWeight:" << lWeight << endl;
    cout << "new 构造函数被调用..." << endl;
    myName = new char[strlen(name) + 1];
    if (!myName) {
        perror("myNmae new failed");
        assert(0);
    }
    age = 18;
    height = 172;
    memcpy(myName, name, strlen(name));
    cout << "myName:" << myName << "gender:" << gender << "weight:" << weight << endl;

}

Human::Human(Human &am):gender(am.gender),weight(am.weight) {

    iNumber++;
    cout << "复制构造函数被调用" << endl;
    myName = new char[strlen(am.myName) + 1];
    if (!myName) {
        perror("myNmae new failed");
        assert(0);
    }
    memcpy(myName, am.myName, strlen(am.myName));
    cout << "my:" << myName << endl;
    age = am.age;
    height = am.height;
}

Human::~Human(){

    if (myName) {
        cout << "delete 析构函数被调用...%p" << myName << endl;
        delete myName;
    }

}

int main() {

    char gg[5] = "nan";
    char *gg1 = gg;
    Human man("tianxuhong", gg1, 110);
    Human human1 = man;
    man.printf();
    man.~Human();
    human1.printf();

    cout<<"object count:"<<Human::iNumber<<endl;

    return 0;
}

 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值