MST

星途 面试题库

面试题:C++ 中函数指针与指针函数的基础应用

请编写一段 C++ 代码,分别定义一个指针函数和一个函数指针,并在 `main` 函数中调用它们。其中指针函数接受两个整数参数并返回它们的和的指针,函数指针指向一个接受两个浮点数参数并返回它们乘积的函数。
21.6万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
#include <iostream>

// 指针函数,接受两个整数参数并返回它们的和的指针
int* sumFunction(int a, int b) {
    int* result = new int(a + b);
    return result;
}

// 普通函数,接受两个浮点数参数并返回它们的乘积
float multiplyFunction(float a, float b) {
    return a * b;
}

int main() {
    // 调用指针函数
    int num1 = 3, num2 = 5;
    int* sumPtr = sumFunction(num1, num2);
    std::cout << "Sum of " << num1 << " and " << num2 << " is: " << *sumPtr << std::endl;
    delete sumPtr;

    // 定义函数指针,指向 multiplyFunction
    float (*multiplyPtr)(float, float) = multiplyFunction;
    float floatNum1 = 2.5f, floatNum2 = 3.5f;
    float product = multiplyPtr(floatNum1, floatNum2);
    std::cout << "Product of " << floatNum1 << " and " << floatNum2 << " is: " << product << std::endl;

    return 0;
}