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

时间:2022-09-09 16:53:18
//
// 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;
}