C++的一些笔记

发现一些小的知识点长期不用都得忘,决定再次遇到了一定要记录一下。

const 成员函数

  • const对象只能调用const成员函数。
  • const对象的值不能被修改,在const成员函数中修改const对象数据成员的值是语法错误
  • 在const函数中调用非const成员函数是语法错误

任何不会修改数据成员的函数都应该声明为const类型。如果在编写const成员函数时,不慎修改了数据成员,或者调用了其它非const成员函数,编译器将指出错误,这无疑会提高程序的健壮性。

explicit 关键字

在构造函数前加explicit关键字禁止对象作隐式转换

#include<iostream>
#include<string>
class Buffer
{
public:
    explicit Buffer(std::string s)
    { 
        str = s; 
        std::cout<<s<<std::endl;
    }
private:
    std::string str;
};

int main()
{
    std::string  s("hello");
    Buffer  buf = s; //隐式转换
    return 0;
}

buf = s 会隐式调用构造函数Buffer(s) , 因为禁止隐式转换,所以编译报错。

去掉explicit后:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/lyh__521/article/details/50602844