#include <iostream>
using namespace std;
int main()
{
cout << "Hello, world!" << endl;
return 0;
}
// iostream 这样的文件为头文件,支持一定的工具。此处编译会将iostream的文件内容添加到程序中。这是为什么呢?这涉及程序和外部世界之间的通信。io指的是输入和输出。当用 cout 时,iostream 文件和源代码文件取代代码行#include ,编译下个阶段使用该文件。
// using 编译指令,使得std名称空间所有名称都可用。这是一种偷懒的做法,using std::cout; 也可以输出,且不存在冲突等潜在问题。
//重要思想 类,封装,继承
类:描述对象行为/状态的模板/蓝图。
class Box
{
public:
double length; // 盒子的长度
double breadth; // 盒子的宽度
double height; // 盒子的高度
};
封装:通过封装,可以将一部分属性和操作隐藏起来,不让使用者访问;另一部分作为类的外部接口,使用者可以访问。封装为程序设计者提供了保护机制。封装的类可以保护类的一些属性和操作不被误使用。
继承:世界是层次化的,就像计算机的组成。从0-1 数字信号的电容,到集成电路,到芯片和软件、系统,都是层次分明的,互相联系又互不相连,可以说是一种继承的关系。(计算机网络当中,应用层,TCP,IP,数据链路层也存在这样的关系)
#include <iostream>
using namespace std;
// 基类
class Shape
{
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
// 派生类
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};
int main(void)
{
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
// 输出对象的面积
cout << "Total area: " << Rect.getArea() << endl;
return 0;
}