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字,可根据实际需要进行扩充。)

相关推荐
郑州光合科技余经理6 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1236 天前
matlab画图工具
开发语言·matlab
dustcell.6 天前
haproxy七层代理
java·开发语言·前端
norlan_jame6 天前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone6 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054966 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
遥遥江上月6 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js
m0_531237176 天前
C语言-数组练习进阶
c语言·开发语言·算法
Railshiqian6 天前
给android源码下的模拟器添加两个后排屏的修改
android·开发语言·javascript
雪人不是菜鸡6 天前
简单工厂模式
开发语言·算法·c#