简介
C++在C语言的基础上增加了面向对象编程,类是C++的核心特性,是一种封装了数据与函数的组合,类其中的数据成为成员变量,函数称为成员函数。
类在一定程度上与结构体相似。
类的定义
使用关键字class定义类
class 类名
{
访问修饰符:
date members;//成员变量--变量
member function();//成员函数--方法
};
访问修饰符:
1.public--公共成员
2.protected--保护成员
3.private--私有成员
例:
#include <iostream>
using namesapce std;
class book
{
public:
char author[10];
char name[10];
int price;
int getprice();//函数声明
void set(char author1, char name1, int price1);//函数声明
};
//成员函数的定义
int getprice()
{
return price;
}
void set(char author1, char name1, int price1)
{
strcopy(author, author1);
strcopy(name, name1);
price = price1;
//该函数调用时为三个成员变量赋值
}
int main()
{
book book1;//定义一个类book1
book1.author = "狂人日记";
book1.name = "鲁迅";
book1.price = 20;
//这里采用的是直接定义类成员变量的方式,也可以使用set函数进行定义
int bookprice = 0;
bookprice = book1.getprice();
cout<<"书的价格为:"<<bookprice<<endl;
return 0;
}