对象的使用
-
什么是对象?
对象,是一个特定“类”的具体实例。 -
对象和普通变量有什么区别?
一般地,一个对象,就是一个特殊的变量,但是有跟丰富的功能和用法。 -
什么时候使用对象?
-
对象的具体使用方法
方式一, 普通对象调用成员函数
Human.h
#pragma once
#include <string>
using namespace std;
//定义一个"人类"
class Human {
// public: 公有的
public:
void eat(); //吃饭
void sleep(); //睡觉
void play(); //玩耍
void work(); //工作
// private: 私有的
private:
string name; //姓名
string sex; //性别
int age; //年龄
};
Human.cpp
#include "Human.h"
#include <iostream>
void Human::eat() {
cout << "吃炸鸡, 喝啤酒!" << endl;
}
void Human::sleep() {
cout << "我在睡觉!" << endl;
}
void Human::play(){
cout << "我在打篮球!" << endl;
}
void Human::work(){
cout << "我在敲代码!" << endl;
}
main.cpp
#include <iostream>
#include <Windows.h>
#include "Human.h"
using namespace std;
int main(void) {
// 定义了一个 zhangsan 对象
Human zhangsan;
//调用类的成员函数
zhangsan.eat();
zhangsan.play();
zhangsan.sleep();
zhangsan.work();
system("pause");
return 0;
}
总结:
1.“.”的使用
2.调用方法时,方法名后需要带一对圆括号()
3.通过对象,只能调用这个对象的public方法
分析:
多个不同的对象都有自己的数据,彼此无关。
方式二, 使用指针对象调用成员函数
main.cpp
#include <iostream>
#include <Windows.h>
#include "Human.h"
using namespace std;
int main(void) {
// 定义了一个 zhangsan 对象
Human zhangsan;
//定义一个Human类型的指针,指向对象 zhangsan
Human* p = &zhangsan;
//使用指针调用类的成员函数
p->eat();
p->play();
p->sleep();
p->work();
//非法使用, 直接访问私有成员, 将无法通过编译
//cout << "年龄" << p->age << endl;
system("pause");
return 0;
}
总结:
’ -> ’ 的使用(类似C语言的结构体用法)