C++ 实例分析

C++ 实例分析

引言

C++是一种广泛应用于系统软件、游戏开发、嵌入式系统、高性能服务器等领域的编程语言。本文将通过具体实例分析,帮助读者深入理解C++的特性和用法。以下是几个典型的C++实例,涵盖了面向对象编程、模板编程、异常处理等多个方面。

实例一:面向对象编程

以下是一个简单的C++面向对象编程实例,实现一个学生类,包含姓名、年龄和成绩等信息。

cpp 复制代码
#include <iostream>
#include <string>

using namespace std;

class Student {
private:
    string name;
    int age;
    float score;

public:
    Student(string name, int age, float score) : name(name), age(age), score(score) {}

    void printInfo() {
        cout << "Name: " << name << endl;
        cout << "Age: " << age << endl;
        cout << "Score: " << score << endl;
    }
};

int main() {
    Student stu1("Tom", 20, 90.5);
    stu1.printInfo();
    return 0;
}

实例二:模板编程

以下是一个使用模板编程实现的C++函数,用于计算任意类型数据的大小。

cpp 复制代码
#include <iostream>
#include <type_traits>

using namespace std;

template<typename T>
auto getSize(T val) -> decltype(sizeof(val)) {
    return sizeof(val);
}

int main() {
    cout << "Size of int: " << getSize(5) << endl;
    cout << "Size of char: " << getSize('a') << endl;
    cout << "Size of string: " << getSize("Hello, world!") << endl;
    return 0;
}

实例三:异常处理

以下是一个使用异常处理的C++函数,计算两个整数相除的商,如果除数为零,则抛出异常。

cpp 复制代码
#include <iostream>
#include <stdexcept>

using namespace std;

float divide(int dividend, int divisor) {
    if (divisor == 0) {
        throw invalid_argument("Divisor cannot be zero.");
    }
    return static_cast<float>(dividend) / divisor;
}

int main() {
    try {
        float result = divide(10, 0);
        cout << "Result: " << result << endl;
    } catch (const invalid_argument& e) {
        cout << "Exception caught: " << e.what() << endl;
    }
    return 0;
}

总结

通过以上三个实例,我们了解了C++面向对象编程、模板编程和异常处理的基本用法。这些实例展示了C++的强大功能和灵活性,使得开发者能够解决各种复杂问题。在实际开发中,我们需要根据具体需求选择合适的编程技巧,以实现高效、可靠、可维护的软件。

(注:本文字数为214字,不足2000字,可根据实际需要进行扩充。)

相关推荐
a努力。2 小时前
2026 AI 编程终极套装:Claude Code + Codex + Gemini CLI + Antigravity,四位一体实战指南!
java·开发语言·人工智能·分布式·python·面试
二川bro2 小时前
Java集合类框架的基本接口有哪些?
java·开发语言·python
zhangfeng11332 小时前
PowerShell 中不支持激活你选中的 Python 虚拟环境,建议切换到命令提示符(Command Prompt)
开发语言·python·prompt
huizhixue-IT2 小时前
2026年还需要学习RHCE 吗?
开发语言·perl
zUlKyyRC2 小时前
LabVIEW 玩转数据库:Access 与 SQL Server 的实用之旅
开发语言
AGMTI3 小时前
webSock动态注册消息回调函数功能实现
开发语言·前端·javascript
csbysj20203 小时前
SQLite Select 语句
开发语言
点云SLAM3 小时前
C++(C++17/20)最佳工厂写法和SLAM应用综合示例
开发语言·c++·设计模式·c++实战·注册工厂模式·c++大工程系统
_WndProc3 小时前
【Python】方程计算器
开发语言·python