Effective C++ (1.让自己习惯C++) ——阅读笔记

文章目录

  • 1.让自己习惯C++
    • 条款01:视C++为一个语言联邦
    • 条款02:尽量以```const```,```enum```,```inline```替换```#define```
    • 条款03:尽可能使用```const```

1.让自己习惯C++


条款01:视C++为一个语言联邦

C++是一个由相关语言组成的联邦,而非单一语言

  • C
  • Object-Oriented C++
  • Template C++
  • STL

条款02:尽量以constenuminline替换#define

  • #define不是语言的一部分,预处理器处理后编译器看不到
// 会导致目标码中多次出现1.653
#define ASPECT_RATIO 1.653
  • 可以用enum代替部分#define

条款03:尽可能使用const

  • 告诉编译器该变量的值不能被改动
/**
 * g++ term03.cpp -o app && ./app
 * 
 * const在星号左边,被指物是常量;在星号右边,指针是常量;在星号两边,指针和被指物都是常量。
 * 
 */

#include 
#include 
using namespace std;

void f1(char *p)
{
    p[0] = 'a';
}

void f2(const char *p)
{
    // f1(p); // error: invalid conversion from ‘const char*’ to ‘char*’ [-fpermissive]
}

void f3(char *const p)
{
    f1(p);
    // p = NULL; //error: assignment of read-only parameter ‘p’
}

void f4(const char *s)
{
    cout << "const char*" << endl;
}

void f4(char *s)
{
    cout << "char*" << endl;
}

int main()
{
    char greeting[] = "hello";
    char *p0 = greeting;
    // p1和p2等价
    const char *p1 = greeting;
    char const *p2 = greeting;
    char *const p3 = greeting;
    const char *const p4 = greeting;

    *p0 = 'a';
    // *p1 = 'a'; //error: assignment of read-only location ‘* p1’
    // *p2 = 'a'; //error: assignment of read-only location ‘* p2’
    *p3 = 'a';
    // *p4 = 'a'; //error: assignment of read-only location ‘*(const char*)p4’

    p1 = NULL;
    p2 = NULL;
    // p3 = NULL; //error: assignment of read-only variable ‘p3’
    // p4 = NULL; //error: assignment of read-only variable ‘p4’

    vector<int> arr = {1, 2, 3};
    const vector<int>::iterator iter = arr.begin(); // iter相当于 T* const
    *iter = 10;
    // iter++; //error: passing ‘const iterator {aka const __gnu_cxx::__normal_iterator >}’ as ‘this’ argument discards qualifiers [-fpermissive]

    vector<int>::const_iterator cIter = arr.begin();
    // *cIter = 11; // error: assignment of read-only location ‘cIter.__gnu_cxx::__normal_iterator >::operator*()’
    cIter++;

    f4("hahha");  // const char*
    f4(greeting); // char*

    return 0;
}

你可能感兴趣的:(Effective C++ (1.让自己习惯C++) ——阅读笔记)