在C++中,类是对象的抽象,对象是类的实例化,类是不存在现实中的,对象是存在现实中的。例如,我们都是人类,人类是一个类,在现实中并不存在人类这个东西,而只存在人这个人类实例化的东西,所以,认识一个对象。所谓类,就是对一群具有相似属性的对象的抽象。
class Name
{
public:
...;
private:
...;
protectde:
...;
}
#include
using namespace std;
class Box
{
// color默认是私有的
char color;
// public:共有成员,类的外部都是可以访问的
public:
double length;
double breadth;
double height;
// 定义类成员函数
// 成员函数可以操作类的任意对象
double get(void);
void set(double len, double bre, double hei);
void set_name(char s);
char get_name(void);
// private:私有成员,除了类和友元函数,类的外部是不可以访问的,派生类也不可以访问
// 在类中,成员默认是私有的
// 要想更改私有成员,只能使用类中的函数或友元函数
private:
char name;
protected:
double weight;
};
// 类的派生,派生类可以访问父类中的protected类型
class SmallBox : Box
{
public:
void set_weight(double wei);
double get_weight(void);
};
void SmallBox::set_weight(double wei)
{
weight = wei;
}
double SmallBox::get_weight(void)
{
return weight;
}
// 使用范围解析符定义函数,注意一定要指定类名
double Box::get(void)
{
return length * breadth * height;
}
void Box::set(double len, double bre, double hei)
{
length = len;
breadth = bre;
height = hei;
}
void Box::set_name(char s)
{
name = s;
}
char Box::get_name(void)
{
return name;
}
int main()
{
double volume[2];
Box box1;
Box box2;
box1.height = 10;
box1.breadth = 10;
box1.length = 10;
volume[0] = box1.get();
box2.set(100, 100, 100);
volume[1] = box2.get();
cout << "volume of box1:" << volume[0] << endl;
cout.precision(3);
// 以小数点输出:fixed
cout << fixed << "volume of box2:" << volume[1] << endl;
box1.set_name('a');
cout << "name of box1:" << box1.get_name() << endl;
SmallBox box3;
box3.set_weight(20.0);
cout << "weight of box3:" << box3.get_weight() << endl;
}
[Running] cd "d:\code\package_01\src\" && g++ *.cpp -o test && "d:\code\package_01\src\"test
volume of box1:1000
volume of box2:1000000.000
name of box1:a
weight of box3:20.000