预备知识:
- 使用关键字“class”进行定义
- 什么是接口? 答:接口是一个共享框架,供两个系统交互时使用。
- 类的公共接口通常为成员函数
- 使用关键private和public进行访问控制(private可以省略)
- 定义成员函数时,使用 :: 来标识函数所属的类
- 不同类的成员函数可以拥有相同命名
- 在private中定义的函数只能提供给public中的成员函数使用
类和结构的区别
有且只有一个区别:结构的默认访问类型是public,而类为private
一个简单的类
#include<iostream>
#include<string>
using namespace std;
class temp
{
private:
int a;
float b;
char c;
string d;
void read () {cout << "a,b,c,d的初始为:"<< a << "," << b <<"," << c <<"," << d <<endl;}
public:
void a_in_temp(int a);
void b_in_temp(float b);
void c_in_temp(char c);
void d_in_temp(string d);
void read_temp();
};
void temp::a_in_temp(int test1)
{
a=test1;
}
void temp::b_in_temp(float test2)
{
b=test2;
}
void temp::c_in_temp(char test3)
{
c=test3;
}
void temp::d_in_temp(string test4)
{
d=test4;
}
void temp::read_temp()
{
read();
}
int main()
{
int a = 10;
float b = 10.0;
char c = 'a';
string d = "nihao";
temp test;
test.a_in_temp(a);
test.b_in_temp(b);
test.c_in_temp(c);
test.d_in_temp(d);
test.read_temp();
//这里再提供一个错误用法
//test.a=11;
//a属于类temp中private里的数据成员,但是public中没有main函数,所以不能引用
return 0;
}
运行结果
碎碎念
对于类的理解,我们可以把他想象为一个宿舍,private就是我们的私人物品,除非我们把ta公开(放进public),不然别人(比如这里的main函数)就不能够使用;而public就是公共用品,例如寝室的空调,想用直接调用即可;