关于c++ class的几个知识点

(1)inline成员函数

class Screen {
public:
    typedef std::string::size_type index;
    // implicitly inline when defined inside the class declaration
    char get() const { return contents[cursor]; }
    // explicitly declared as inline; will be defined outside the class declaration
    inline char get(index ht, index wd) const;
    // inline not specified in class declaration, but can be defined inline later
    index get_cursor() const;
    //
};

// inline declared in the class declaration; no need to repeat on the definition
char Screen::get(index ht, index wd) const
{
    index row = ht * width;
    return contents[row + wd];
}

// not declared as inline in the class declaration, but ok to make inline in definition
inline Screen::index Screen::get_cursor() const
{
    return cursor;
}

在类内部定义的成员函数,自动作为inline处理。

可以在类声明时指定inline,也可以在类定义体外部的函数定义上指定inline,后者的好处是使得类比较容易阅读。

inline成员函数的定义必须在调用该函数的每个源文件中可见,所以不在类定义体内定义的inline成员函数,其定义通常应放在有类定义的同一头文件中。

(2)class的前向声明

可以声明一个类而不定义它:

class Screen; // declaration of the Screen class

这个声明称为前向声明(forward declaration)。在Screen声明之后、定义之前,它是一个不完全类型(incomplete type),即已知Screen是一个类型,但不知其包含哪些成员。

不完全类型只能以有限的方式使用。不能定义该类型的对象,只能定义指向该类型的指针或引用,或者用于声明(而不是定义)使用该类型作为形参类型或返回类型的函数。

类的前向声明一般用来编写互相依赖的类。

只要类名一出现,就可以认为该类已声明。所以类的数据成员可以是指向自身类型的指针或引用:

class LinkScreen {
    Screen window;
    LinkScreen * next;
    LinkScreen * prev;
};

【学习资料】 《c++ primer》

posted on 2013-02-17 14:40  zhuyf87  阅读(302)  评论(0编辑  收藏  举报

导航