初学Cpp,学习收获
- 面向对象的实现方式——class 使用的时候用.xxx表示
- public 无权限
- private有权限
- protected
- this指针来访问自己的地址(所有对象都可以),在成员函数的内部,用来指向调用的对象
#include <iostream>
using namespace std;
class Box
{
public:
// 构造函数定义
Box(double l=2.0, double b=2.0, double h=2.0)
{
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
}
double Volume()
{
return length * breadth * height;
}
int compare(Box box)
{
return this->Volume() > box.Volume();
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main(void)
{
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
if(Box1.compare(Box2))
{
cout << "Box2 is smaller than Box1" <<endl;
}
else
{
cout << "Box2 is equal to or larger than Box1" <<endl;
}
return 0;
}
PS:只有成员函数才有this指针,友元函数没有this的用法
- 静态成员(static):无论创建多少个类的对象,静态成员都只有一个副本
普通全局变量和静态变量的联系和区别
地址都是一样的,而且都是存放在RAM之中
但是他们的作用域不同,
静态变量是源文件
全局变量是整个程序
计算机区别他们的方式:通过变量的 linkage (即能否被链接器识别)属性,internal linkage 的变量只能被本文件访问,而 external linkage 的变量可以被其他文件访问。