属性都是私有的,外部不能直接访问。
提供与属性相关的get/set函数,间接访问属性。
静态成员
class Point
{
private:
int x , y;
static int count; //定义静态局部变量
public:
Point(){ count ++ ;};
~Point(){ count -- };
static void showCount(){
cout << count << endl ;} //静态函数只能调用静态变量
Point(Point &p){ // 复制构造函数
x = p.x;
y = p.y;
}
}
static Point::count = 0; // 必须在类外面初始化
count仍然是局部变量,生存期与程序运行时间相同。
可以在构造函数中加上 count ++ ,在析构函数中 加入 count --
复制构造函数 , 用于三种情形:
1,
Point a(10,20);
Point b = a; // 不能分成两行写,必须创建b时赋值
2,传参
void fun1(Point p)
{
cout << p.getX() << endl;
}
3,函数值返回
Point fun2(){
return Point(1,2);
}