C++基础

Posted at:
March 6, 2018
Tags:
CPP

1 简介

本文主要参考 Learn X in Y minutes 上的教程介绍C++相关的基础知识。

相对于C语言,C++具有以下特点:

  • 支持数据的抽象与封装
  • 支持面向对象编程
  • 支持泛型编程

2 头文件

C语言的标准库头文件可以在C++中使用,方法是加上"c"前缀、去掉.h后缀。
C++标准库的头文件使用时也不需要指定后缀,比如说iostream。

3 命名空间

C++引入了命名空间(namespace)概念,为变量、函数、类等提供隔离的作用域,防止命名冲突。
通过namespace关键字可以定义命名空间(允许嵌套)。

通过using namespace可以引入指定命名空间内所有symbol,比如说std命名空间。

又或者只引入某个symbol:

4 输入/输出

C++使用“流”来输入输出。
通过<<插入数据到流中。
通过>>从流中提取数据。
cin、cout、和cerr分别对应stdin(标准输入)、stdout(标准输出)和stderr(标准错误)。

如果需要实现类似于printf这样控制宽度、精度、对齐、进制(base)的效果,有两种选择:

  • 引入cstdio头文件使用printf函数
  • 通过 ios_base类 进行设置

5 字符串

C++中的字符串是string类,提供比char *更好的封装与功能。
可以使用+或者+=拼接字符串(通过运算符重载实现)。
to_string 可以将常见类型转换为string类型。

对于非英文字符串应该使用wstring存储,比如说中文。
string虽然也可以存储,但实际上是以char作为字符单元,类似计算长度、反转等操作结果并不正确。

6 引用

C++提供引用来设置变量别名,本质上是特殊的指针,初始化后不能重新赋值。
使用引用时的语法与原变量相同:不需要通过*解引用。
常量引用不允许改变变量的值。

对于临时对象的常量引用会使其生命周期延长到当前作用域。

另外还有右值引用,因为超出本文范围,建议自行了解。

7 类与面向对象编程

#include <iostream>

// 声明一个类。
// 类通常在头文件(.h或.hpp)中声明。
class Dog {
    // 成员变量和成员函数默认情况下是私有(private)的。
    std::string name;
    int weight;

// 在这个标签之后,所有声明都是公有(public)的,
// 直到重新指定“private:”(私有继承)或“protected:”(保护继承)为止
public:

    // 默认的构造器
    Dog();

    // 这里是成员函数声明的一个例子。
    // 可以注意到,我们在此处使用了std::string,而不是using namespace std
    // 语句using namespace绝不应当出现在头文件当中。
    void setName(const std::string& dogsName);

    void setWeight(int dogsWeight);

    // 如果一个函数不对对象的状态进行修改,
    // 应当在声明中加上const。
    // 这样,你就可以对一个以常量方式引用的对象执行该操作。
    // 同时可以注意到,当父类的成员函数需要被子类重写时,
    // 父类中的函数必须被显式声明为虚函数(virtual)。
    // 考虑到性能方面的因素,函数默认情况下不会被声明为虚函数。
    virtual void print() const;

    // 函数也可以在class body内部定义。
    // 这样定义的函数会自动成为内联函数。
    void bark() const { std::cout << name << " barks!\n" }

    // 除了构造器以外,C++还提供了析构器。
    // 当一个对象被删除或者脱离其定义域时,它的析构函数会被调用。
    // 这使得RAII这样的强大范式(参见下文)成为可能。
    // 为了衍生出子类来,基类的析构函数必须定义为虚函数。
    // 如果没有定义为虚函数,那么通过基类引用或者指针销毁时,衍生类的析构函数并不会被调用。
    virtual ~Dog();

}; // 在类的定义之后,要加一个分号

// 类的成员函数通常在.cpp文件中实现。
void Dog::Dog()
{
    std::cout << "A dog has been constructed\n";
}

// 复杂对象(例如字符串)应当以引用的形式传递,
// 对于不需要修改的对象,最好使用常量引用。
void Dog::setName(const std::string& dogsName)
{
    name = dogsName;
}

void Dog::setWeight(int dogsWeight)
{
    weight = dogsWeight;
}

// 虚函数的virtual关键字只需要在声明时使用,不需要在定义时重复
void Dog::print() const
{
    std::cout << "Dog is " << name << " and weighs " << weight << "kg\n";
}

void Dog::~Dog()
{
    std::cout << "Goodbye " << name << "\n";
}

int main() {
    Dog myDog; // 此时显示“A dog has been constructed”
    myDog.setName("Barkley");
    myDog.setWeight(10);
    myDog.print(); // 显示“Dog is Barkley and weighs 10 kg”
    return 0;
} // 显示“Goodbye Barkley”

7.1 初始化与运算符重载

变量可以直接赋初值,也可以在初始化列表中根据外部参数赋值。
另外C++允许运算符重载,也就是改变运算符(比如说+,*)对于对象的行为。

7.2 继承

继承可以复用已有代码,可以分为单继承、多继承、虚拟继承。
利用多态可以提高灵活性、增加可维护性。
除了继承外,合理使用组合也是不错的选择。

8 模板

C++模板主要用于泛型编程。

template<class T>
class Box {
public:
    // In this class, T can be used as any other type.
    void insert(const T&) { ... }
};

// During compilation, the compiler actually generates copies of each template
// with parameters substituted, so the full definition of the class must be
// present at each invocation. This is why you will see template classes defined
// entirely in header files.

// To instantiate a template class on the stack:
Box<int> intBox;

// and you can use it as you would expect:
intBox.insert(123);

// You can, of course, nest templates:
Box<Box<int> > boxOfBox;
boxOfBox.insert(intBox);

// Until C++11, you had to place a space between the two '>'s, otherwise '>>'
// would be parsed as the right shift operator.

// You will sometimes see
//   template<typename T>
// instead. The 'class' keyword and 'typename' keywords are _mostly_
// interchangeable in this case. For the full explanation, see
//   http://en.wikipedia.org/wiki/Typename
// (yes, that keyword has its own Wikipedia page).

// Similarly, a template function:
template<class T>
void barkThreeTimes(const T& input)
{
    input.bark();
    input.bark();
    input.bark();
}

// Notice that nothing is specified about the type parameters here. The compiler
// will generate and then type-check every invocation of the template, so the
// above function works with any type 'T' that has a const 'bark' method!

Dog fluffy;
fluffy.setName("Fluffy")
barkThreeTimes(fluffy); // Prints "Fluffy barks" three times.

// Template parameters don't have to be classes:
template<int Y>
void printMessage() {
  cout << "Learn C++ in " << Y << " minutes!" << endl;
}

// And you can explicitly specialize templates for more efficient code. Of
// course, most real-world uses of specialization are not as trivial as this.
// Note that you still need to declare the function (or class) as a template
// even if you explicitly specified all parameters.
template<>
void printMessage<10>() {
  cout << "Learn C++ faster in only 10 minutes!" << endl;
}

printMessage<20>();  // Prints "Learn C++ in 20 minutes!"
printMessage<10>();  // Prints "Learn C++ faster in only 10 minutes!"

9 异常处理

10 RAII

RAII指的是“资源获取就是初始化”(Resource Allocation Is Initialization)。
RAII是C++中最强大的编程范式之一。
简单来说,就是在构造函数中申请资源,在析构函数中释放资源。

void doSomethingWithAFile(const char* filename)
{
    // 首先,让我们假设一切都会顺利进行。

    FILE* fh = fopen(filename, "r"); // 以只读模式打开文件

    doSomethingWithTheFile(fh);
    doSomethingElseWithIt(fh);

    fclose(fh); // 关闭文件句柄
}

// 不幸的是,随着错误处理机制的引入,事情会变得复杂。
// 假设fopen函数有可能执行失败,
// 而doSomethingWithTheFile和doSomethingElseWithIt会在失败时返回错误代码。
// (虽然异常是C++中处理错误的推荐方式,
// 但是某些程序员,尤其是有C语言背景的,并不认可异常捕获机制的作用)。
// 现在,我们必须检查每个函数调用是否成功执行,并在问题发生的时候关闭文件句柄。
bool doSomethingWithAFile(const char* filename)
{
    FILE* fh = fopen(filename, "r"); // 以只读模式打开文件
    if (fh == nullptr) // 当执行失败是,返回的指针是nullptr
        return false; // 向调用者汇报错误

    // 假设每个函数会在执行失败时返回false
    if (!doSomethingWithTheFile(fh)) {
        fclose(fh); // 关闭文件句柄,避免造成内存泄漏。
        return false; // 反馈错误
    }
    if (!doSomethingElseWithIt(fh)) {
        fclose(fh); // 关闭文件句柄
        return false; // 反馈错误
    }

    fclose(fh); // 关闭文件句柄
    return true; // 指示函数已成功执行
}

// C语言的程序员通常会借助goto语句简化上面的代码:
bool doSomethingWithAFile(const char* filename)
{
    FILE* fh = fopen(filename, "r");
    if (fh == nullptr)
        return false;

    if (!doSomethingWithTheFile(fh))
        goto failure;

    if (!doSomethingElseWithIt(fh))
        goto failure;

    fclose(fh); // 关闭文件
    return true; // 执行成功

failure:
    fclose(fh);
    return false; // 反馈错误
}

// 如果用异常捕获机制来指示错误的话,
// 代码会变得清晰一些,但是仍然有优化的余地。
void doSomethingWithAFile(const char* filename)
{
    FILE* fh = fopen(filename, "r"); // 以只读模式打开文件
    if (fh == nullptr)
        throw std::exception("Could not open the file.");

    try {
        doSomethingWithTheFile(fh);
        doSomethingElseWithIt(fh);
    }
    catch (...) {
        fclose(fh); // 保证出错的时候文件被正确关闭
        throw; // 之后,重新抛出这个异常
    }

    fclose(fh); // 关闭文件
    // 所有工作顺利完成
}

// 相比之下,使用C++中的文件流类(fstream)时,
// fstream会利用自己的析构器来关闭文件句柄。
// 只要离开了某一对象的定义域,它的析构函数就会被自动调用。
void doSomethingWithAFile(const std::string& filename)
{
    // ifstream是输入文件流(input file stream)的简称
    std::ifstream fh(filename); // 打开一个文件

    // 对文件进行一些操作
    doSomethingWithTheFile(fh);
    doSomethingElseWithIt(fh);

} // 文件已经被析构器自动关闭

11 杂项Misc

11.1 函数重载

C++支持函数重载,也就是可以定义一组名称相同而参数不同的函数。
实现上类似于根据函数名+参数类型生成新的函数名。

11.2 参数默认值设置

可以为函数的参数指定默认值,在调用者没有提供相应参数时按照默认值调用。
具有默认值的参数必须放在所有的常规参数之后。

11.3 空指针

在C++中使用nullptr代替C语言中的NULL。

11.4 严格原型

12 C++新特性

C++语言也在不停地发展,比如说C++11引入了许多有用的新特性,可以留意相关的博文。

13 STL

Modified at: March 6, 2018