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

相关推荐
LDR00615 天前
Type-C 快充全面升级!LDR6601 赋能个人护理便携电机,重塑剃须刀 / 理发器新体验
c语言·开发语言
雪碧聊技术15 天前
Tree.js是什么?一文讲透
开发语言·javascript·ecmascript
码云数智-园园15 天前
C++20 Modules 模块详解
java·开发语言·spring
swordbob15 天前
NIO的channel中什么是 fd(File Descriptor,文件描述符)
java·开发语言·nio
源分享15 天前
Java线程同步的多种实现方法(非常详细)
java·开发语言·jvm
Luminous.15 天前
C语言--day30
c语言·开发语言
何以解忧,唯有..15 天前
Go语言循环语句详解:for、range与循环控制
开发语言·算法·golang
謓泽15 天前
C语言不是语法,是通往机器的地图。
c语言·开发语言
云水一下15 天前
从零开始学 PHP 系列(一):PHP 的前世今生与开发环境搭建
开发语言·php
飞天狗11115 天前
零基础JavaWeb入门——第五课第二小节:九大内置对象 · 第2个:response(响应对象)
java·开发语言