C++的一些关键字用法

const

  • 这个关键字真是太常用了, 所以干脆总结一下.
int const a = 8;            //定义一个int常量a, 不能再给a赋值了
const int a = 8;            //和上面一样

int const *a;               //定义一个常量*a, *a不可变, a可变
const int *a;               //和上面一样

int *const a;               //定义一个常量a, a不可变, *a可变

void fun(const int var)     //定义一个函数, 参数为int型常量
{
}
const int fun(void)         //返回值为常量, 实际上const是画蛇添足, 应该不写
{
}
const myClass fun(void)     //myClass对象中还有成员, 此处const有意义
{
}
int fun() const;            //声明
int fun() const             //声明和定义中均要写const, 表示这个函数
                            //不修改成员变量, 除非那个变量加了mutable
{
}            

mutable

  • 既然提高了这个关键字, 也举个例子, 这个关键字是这样用的:
//表示了变量m是可变的, 与const是反义词
mutable int m;

explicit

  • 该关键字修饰的函数表示, 只能显式调用, 不能隐式调用. 举例说明:
class Test
{
public:
    //声明构造函数只能显式调用
    explicit Test(int n)
    {
        num=n;
    }
private:
    int num;
};
int main()
{
    Test t1(12);//显式调用成功
    Test t2 = 12;//编译错误,不能隐式调用该构造函数
    return 0;
}
posted @ 2018-03-05 22:33  技术不支持  阅读(327)  评论(0编辑  收藏  举报