在面向对象程序设计中,一个对象表示现实世界中一个独一无二的实体。
相同类型的对象用一个通用的类来定义。一个类是指一个模板、蓝图或者约定,定义了对象具有什么样的数据域和函数。
一个对象就是一个类的实例,我们可以创建一个类的多个实例。
对于类模板和对象的图示,我们可以用UML(Unified Modeling Language, 统一建模语言)表示法将其标准化。
首先,我们画一个圆类的UML类图。
- 表格分成三部分:类名、数据域、构造函数和函数
- 加号"+"表示公有域,函数名(参数类型):返回值
练习1:创建三个半径不同的“圆”对象,打印输出每个对象的半径和面积,并且修改第二个对象的半径并输出。
参考代码:
#include "pch.h"
#include <iostream>
using namespace std;
class Circle
{
public:
double radius;
Circle() //默认的构造函数
{
radius = 1;
}
Circle(double newRadius) //有参数的构造函数。
{
radius = newRadius;
}
double getArea()
{
return radius * radius * 3.14159;
}
};
int main()
{
Circle circle1(1.0);
Circle circle2(25);
Circle circle3(125);
cout << "The area of the circle of radius " << circle1.radius << " is " << circle1.getArea() << endl;
cout << "The area of the circle of radius " << circle2.radius << " is " << circle2.getArea() << endl;
cout << "The area of the circle of radius " << circle3.radius << " is " << circle3.getArea() << endl;
circle2.radius = 100;
cout << "The area of the circle of radius " << circle2.radius << " is " << circle2.getArea() << endl;
return 0;
}
答案: