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

本文介绍了C++编程中内联函数的定义与使用,包括在类内部和类定义体外部的声明方式。同时,文章阐述了类的前向声明及其在编写互相依赖类时的应用,提供了实例解析。

(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》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值