#include <iostream>
#include <Windows.h>
#include <string>
using namespace std;
//定义一个“人类”
class Human {
public: //公有的,对外的
//手动的构成函数
/*Human(){} ///这个就是手动构成的函数,内部法*/
Human();
void eat(); //方法,成员函数
void sleep();
void play(); //根据需求来,对外的
/* void work() {
//内联函数
}*/
void work();
string getName();
int getAge();
int getSalary();
private: //私有的,内部的
string name;
int age = 18; //类内初始值,C++11才支持
int salary;
};
void Human::eat(){ //加一个类的名字和两个冒号,限制它是类的方法
cout << "吃炸鸡,喝啤酒!" << endl;
}
void Human::sleep() {
cout << "我正在睡觉!" << endl;
}
void Human::play() {
cout << "我在K歌!" << endl;
}
void Human::work() {
cout << "我在工作!" << endl;
}
string Human::getName() { //目的是搞封装,保护隐私
return name;
}
int Human::getAge() {
return age;
}
int Human::getSalary() {
return salary;
}
Human::Human() { //手动构成函数,外部的。这是自动会调用
name = "无名";
age = 24;
salary = 40000;
}
int main(void) {
//使用已经定义的类Human来创建一个对象
Human h1;
//cout << "年龄:" << h1.getAge() << endl;
/*
//使用方法
h1.eat();
h1.play();
h1.sleep();
*/
/*
//或者指针方法
Human *p;
p = &h1;
p->eat();
p->play();
p->sleep();
/*cout << h1.age << endl; */ //非法的,不能直接访问private里面的
/*
cout << h1.getAge() << endl;
*/
//使用类Human创建一个对象zhangsan
//创建一个对象时必须调用构成函数
Human zhangsan; //此时,调用的构造函数就是“默认构造函数”,当找不到时,就会自动生成一个“合成构造函数”
cout << zhangsan.getAge() << endl;
cout << zhangsan.getSalary() << endl;
cout << zhangsan.getName() << endl;
system("pause");
return 0;
}
类以及对象,自定义重载构造函数
最新推荐文章于 2024-09-20 20:43:57 发布
本文详细介绍了C++中如何定义类(如Human类),包括公有和私有成员的使用,构造函数(如默认构造函数)的应用,以及对象的创建和封装。展示了如何通过对象调用成员函数和访问属性。
摘要由CSDN通过智能技术生成