自定义的重载构造函数
- 实际开发中可以根据需要定义多个构造函数
定义:
Human(int age, string name, string sex);
实现:
Human::Human(int age, string name, string sex){
//私有数据初始化
//this访问的就是自己的私有数据
//把外部传递的参数赋值给私有数据
this->name = name;
this->sex = sex;
this->age = age;
}
调用:
Human zhangsan(18, "张三", "男");
Human.h
#pragma once
#include <string>
using namespace std;
//定义一个"人类"
class Human {
public:
//定义了一个自定义重载构造函数
Human(int age, string name, string sex);
string getName();
string getSex();
int getAge();
private:
string name; //姓名
string sex; //性别
int age; //年龄
};
Human.cpp
#include "Human.h"
#include <iostream>
Human::Human(int age, string name, string sex){
//私有数据初始化
//this访问的就是自己的私有数据
//把外部传递的参数赋值给私有数据
this->name = name;
this->sex = sex;
this->age = age;
}
string Human::getName(){
return name;
}
string Human::getSex(){
return sex;
}
int Human::getAge(){
return age;
}
main.cpp
#include <iostream>
#include <Windows.h>
#include "Human.h"
using namespace std;
int main(void) {
//定义了一个 zhangsan 对象
//此时, 调用的就是自定义重载构造函数
Human zhangsan(18, "张三", "男");
cout << "姓名: " << zhangsan.getName() << endl;
cout << "年龄: " << zhangsan.getAge() << endl;
cout << "姓别: " << zhangsan.getSex() << endl;
system("pause");
return 0;
}