C++98 标准详解:C++的首次标准化

C++98(ISO/IEC 14882:1998)是C++语言的第一个国际标准版本,正式名称为"C++ Programming Language, First Edition"。它基于之前的C++实现(通常称为"pre-standard C++“或"Cfront C++”)进行了标准化和规范化。

一、C++98相较于pre-standard C++的主要改进

1. 标准模板库(STL)的引入

#include <vector>
#include <algorithm>

std::vector<int> v;  // 动态数组容器
v.push_back(10);
std::sort(v.begin(), v.end());  // 通用算法

2. 命名空间(namespace)

namespace MyLib {
    class Widget {};
    void helper() {}
}

MyLib::Widget w;  // 避免命名冲突

3. 布尔类型(bool)

bool flag = true;  // 专门的布尔类型
if (flag) {
    // ...
}

4. 异常处理

try {
    throw std::runtime_error("Error");
} catch (const std::exception& e) {
    std::cerr << e.what();
}

5. 运行时类型识别(RTTI)

class Base { virtual ~Base() {} };
class Derived : public Base {};

Base* b = new Derived;
if (Derived* d = dynamic_cast<Derived*>(b)) {
    // 转换成功
}

6. 显式类型转换操作符

class String {
public:
    explicit String(int size);  // 禁止隐式转换
};

7. mutable关键字

class Cache {
    mutable int accessCount;  // 可在const方法中修改
public:
    int get() const { 
        ++accessCount;
        return 42;
    }
};

8. 模板改进

template <typename T>
T max(T a, T b) {  // 函数模板
    return a > b ? a : b;
}

template <typename T, int N>
class Array {  // 非类型模板参数
    T data[N];
};

二、标准库组件

1. 容器

#include <vector>
#include <list>
#include <map>
#include <set>

std::vector<int> v;
std::list<std::string> lst;
std::map<std::string, int> phonebook;
std::set<double> uniqueValues;

2. 算法

#include <algorithm>

std::vector<int> v = {3, 1, 4};
std::sort(v.begin(), v.end());
int* p = std::find(&v[0], &v[3], 4);

3. 字符串类

#include <string>

std::string s = "Hello";
s += " World";
size_t len = s.length();

4. 输入输出流

#include <iostream>
#include <fstream>
#include <sstream>

std::ifstream file("data.txt");
std::string line;
while (std::getline(file, line)) {
    std::cout << line << '\n';
}

5. 数值限制

#include <limits>

int max_int = std::numeric_limits<int>::max();

三、其他重要特性

1. 类型定义(typedef)

typedef std::map<std::string, std::vector<int>> ComplexMap;

2. 静态成员初始化

class Math {
public:
    static const double PI;
};
const double Math::PI = 3.141592653589793;

3. 默认参数

void drawCircle(int x, int y, int radius = 10);

4. 函数重载

void print(int i);
void print(const std::string& s);

5. 友元函数

class Box {
    double width;
public:
    friend void printWidth(Box box);
};

void printWidth(Box box) {
    std::cout << box.width;
}

四、与C的兼容性和区别

1. 头文件命名

#include <iostream>    // C++风格
#include <stdio.h>     // C风格
#include <cstdio>      // C++包装的C库

2. 函数原型要求

// C++要求完整函数原型
void func(int);  // 声明
void func(int x) { /*...*/ }  // 定义

3. const含义

const int MAX = 100;  // C++中具有内部链接性

五、总结

C++98标准的主要贡献:

  1. 标准化:统一了各种C++实现的不同行为
  2. STL引入:提供了强大的通用容器和算法
  3. 类型系统增强:增加了bool类型和RTTI支持
  4. 异常处理:标准化的错误处理机制
  5. 模板规范化:定义了模板的标准行为
  6. 标准库:建立了完整的C++标准库体系

C++98奠定了现代C++的基础,虽然相比后续版本功能较为基础,但至今仍然是许多嵌入式和老旧系统的主要C++标准。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐