C++编程规范,包括命名约定、代码组织风格和最佳实践

// 重点演示如何通过清晰的命名和结构化的代码实现整洁性和可维护性。
// 遵循Google C++风格指南的核心原则,适用于通用C++开发场景。

// timer.cpp - 计时器类实现示例
#include <chrono>
#include <string>

// 类名使用大驼峰命名法(UpperCamelCase)
class Timer {
public:
    // 构造函数使用显式声明避免隐式转换
    explicit Timer(const std::string& name) 
        : timer_name_(name), 
          is_running_(false) {
        // 初始化列表优先于构造函数内赋值
    }

    // 公共成员函数使用小驼峰命名法(lowerCamelCase)
    void startTimer() {
        if (!is_running_) {
            start_time_ = std::chrono::steady_clock::now();
            is_running_ = true;
        }
    }

    // 常量成员函数使用const修饰
    double getElapsedTime() const {
        if (is_running_) {
            auto current_time = std::chrono::steady_clock::now();
            auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(
                current_time - start_time_);
            return duration.count() / 1000.0;
        }
        return 0.0;
    }

    // 布尔类型函数使用is/has/can等前缀
    bool isRunning() const {
        return is_running_;
    }

    // 设置函数使用set前缀,获取函数使用get前缀
    void setTimerName(const std::string& name) {
        timer_name_ = name;
    }

    const std::string& getTimerName() const {
        return timer_name_;
    }

private:
    // 私有成员变量使用后缀下划线区分
    std::string timer_name_;
    std::chrono::steady_clock::time_point start_time_;
    bool is_running_;
};

// 自由函数使用小写加下划线命名法(snake_case)
void demonstrate_timer_usage() {
    Timer my_timer("示例计时器");  // 局部变量使用小写加下划线
    
    my_timer.startTimer();
    
    // 重要的代码段使用空行分隔逻辑块
    if (my_timer.isRunning()) {
        double elapsed = my_timer.getElapsedTime();
        // 避免魔法数字,使用有意义的常量
        const double timeout_threshold = 5.0;
        
        if (elapsed > timeout_threshold) {
            // 错误处理放在函数开始处
        }
    }
}

// 常量使用k前缀和大写蛇形命名法
const int kMaxTimerCount = 10;
const std::string kDefaultTimerName = "未命名计时器";

// 枚举类使用大驼峰命名法
enum class TimerState {
    kStopped,   // 枚举值使用k前缀
    kRunning,
    kPaused
};
posted @ 2026-01-06 08:22  让泪化作相思雨  阅读(24)  评论(0)    收藏  举报