溫馨提示×

c++ example如何展示最佳實踐

c++
小樊
81
2024-09-27 18:02:47
欄目: 編程語言

在C++中,展示最佳實踐通常涉及以下幾個方面:代碼風(fēng)格、效率、可維護性、錯誤處理和文檔化。下面是一個簡單的C++程序示例,展示了這些最佳實踐:

#include <iostream>
#include <vector>
#include <stdexcept>

// 最佳實踐1: 使用有意義的命名
class Circle {
public:
    Circle(double radius) : radius_(radius) {}

    // 最佳實踐2: 使用范圍for循環(huán)簡化迭代
    void printArea() const {
        std::cout << "Area: " << 3.14159 * radius_ * radius_ << std::endl;
    }

private:
    double radius_; // 最佳實踐3: 使用私有成員變量,并通過公共方法訪問
};

// 最佳實踐4: 使用異常處理錯誤情況
double calculateArea(const std::vector<double>& radii) {
    if (radii.empty()) {
        throw std::invalid_argument("Radii vector cannot be empty.");
    }

    double totalArea = 0.0;
    for (const double& radius : radii) {
        if (radius <= 0) {
            throw std::invalid_argument("Radius must be positive.");
        }
        totalArea += 3.14159 * radius * radius;
    }

    return totalArea;
}

int main() {
    try {
        // 最佳實踐5: 使用std::vector代替原生數(shù)組
        std::vector<double> radii = {5.0, 10.0, 15.0};

        // 最佳實踐6: 使用const引用傳遞大型對象以節(jié)省內(nèi)存和提高性能
        const std::vector<double>& constRadii = radii;

        // 最佳實踐7: 使用智能指針管理動態(tài)分配的內(nèi)存(本例中未使用,但為示例完整性提及)
        // std::unique_ptr<std::vector<double>> smartRadii(new std::vector<double>(radii));

        Circle circle(5.0);
        circle.printArea();

        double total = calculateArea(constRadii);
        std::cout << "Total area: " << total << std::endl;
    } catch (const std::invalid_argument& e) {
        // 最佳實踐8: 使用std::cerr輸出錯誤信息
        std::cerr << "Error: " << e.what() << std::endl;
        return 1;
    }

    return 0;
}

這個示例展示了以下最佳實踐:

  1. 使用有意義的命名(如Circle、radius_)。
  2. 使用范圍for循環(huán)簡化迭代(如for (const double& radius : radii))。
  3. 使用私有成員變量,并通過公共方法訪問(如private: double radius_;public: double getRadius() const { return radius_; })。
  4. 使用異常處理錯誤情況(如throw std::invalid_argument("Radii vector cannot be empty.");)。
  5. 使用std::vector代替原生數(shù)組。
  6. 使用const引用傳遞大型對象以節(jié)省內(nèi)存和提高性能。
  7. 使用智能指針管理動態(tài)分配的內(nèi)存(本例中未使用,但為示例完整性提及)。
  8. 使用std::cerr輸出錯誤信息。

0