类(class)
类的基本思想是抽象(data abstraction)与封装 (encapsulation) 。 类的定义:
成员函数(Member function) 必须在类内部声明(declare),而在类内部定义(define)的函数为隐式内联(inline) ,在类外部定义用范围操作符::。this指针 在生成对象时隐式生成且绑定对象地址,不可改变(type *const this)。const成员函数
type get_value ( ) const { return value; }
type get_value ( const type * const this ) { return this - > value; }
返回this对象的函数的类型为reference,而引用结果为左值,且返回的是对象本身,而非拷贝对象。 object_type & combine ( )
{
return * this ;
}
istream & read ( istream & is) { return is; }
构造函数(construct) 用于初始化类成员,在对象被创造时被调用。
默认构造函数 只在没有定义构造函数时调用;不能够初始化类内部的没有默认构造函数的类成员。 Object ( ) = default ;
Object ( const_type m1, const_type m2) : m1 ( m1) , m2 ( m2) { }
Object ( ) : Object ( m1, m2) { }
类成员的类型为const, reference的必须初始化。 Copy, Assignment, and Destruction ,一些需要动态内存分配的类可以使用vector或者string处理内存。委托构造函数(Delegating Construct) 使用其他的构造函数实现初始化。explicit 阻止使用该构造函数。 explicit Object ( const type& s) : S ( s) { } ;
Object obj= s;
Object obj ( s) ;
类的访问控制与封装:
友元(Friends) 可以访问类内非public成员,它在类内部声明。 class Object {
friend type fact ( ) ;
friend class_type men;
friend type class_type:: fun ( ) ;
} ;
增加类的特征:
类型成员(Type Member) 需要定义在类的首部 public :
typedf std:: string:: size_type pos;
using pos = std:: string:: size_type;
类的域(Class Scope):
typedef double Money;
class Object
{
typedef double Money;
. . .
}
综合类(Aggregate Class) 的所有成员都是public,没有构造函数及类内初始化,赋值要注意顺序。
struct Person
{
string name;
unsigned age;
}
Person p = { 'Mike' , 3 } ;
静态类成员(Static Class MeMber)