MST

星途 面试题库

面试题:C++函数模板基础应用

请编写一个C++函数模板,用于交换两个不同类型变量的值,并在主函数中调用该模板,分别交换两个整数和两个浮点数的值。
13.3万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
#include <iostream>

// 函数模板定义
template<typename T>
void swapValues(T& a, T& b) {
    T temp = a;
    a = b;
    b = temp;
}

int main() {
    int num1 = 5, num2 = 10;
    std::cout << "交换前: num1 = " << num1 << ", num2 = " << num2 << std::endl;
    swapValues(num1, num2);
    std::cout << "交换后: num1 = " << num1 << ", num2 = " << num2 << std::endl;

    float float1 = 3.14f, float2 = 2.71f;
    std::cout << "交换前: float1 = " << float1 << ", float2 = " << float2 << std::endl;
    swapValues(float1, float2);
    std::cout << "交换后: float1 = " << float1 << ", float2 = " << float2 << std::endl;

    return 0;
}