默认情况下类的成员是私有 的,而结构体(struct)中的成 员是公有的。
setData(float, float); calcArea( ); getWidth( ); getLength( ); getArea( );
8.2 类的基本概念(续)
• 为了使类的成员能够在类外面被访问,其 成员必须定义为public. • Example:
Rectangle.h Rectangle.cpp 8-2.cpp
8.6 私有函数成员的作用
• 专门用于内部处理的函数,它们在类的外部不能 使用,这些函数为私有的。 • 私有函数可以被同一个类中的其它函数调用。 Example: class Rectangle { private: float width, length , area; void calcArea( ); public: … 26 };
7
class Rectangle { private: float width; float length: float area; public: void setData(float, float); void calcArea( ); float getWidth( ); float getLength( ); float getArea( ); };
31
8.8.1 构造函数
• 构造函数是与类同名的函数成员; • 没有返回值类型,也不允许有void; • 如果构造函数没有参数,则称为缺省构造函数; • 构造函数的作用:在对象被创建时,采用给定的值将 对象初始化为一个特定的状态。 • 在对象创建时,由系统自动调用; • 如果程序中未声明,则系统自动产生出一个缺省形式 的构造函数; • 允许为内联函数、重载函数、带缺省形参值的函数。