MST

星途 面试题库

面试题:C++模板类派生新类中的模板参数传递与重定义

假设有一个模板类`Base`,其模板参数为`T`和`U`,`Base`类有一个成员函数`func`返回`T`类型和`U`类型变量的和。现在从`Base`类派生出`Derived`类,要求`Derived`类能够重新定义`func`函数,实现返回`T`类型变量的两倍与`U`类型变量的乘积,并且在`Derived`类的构造函数中,根据传递进来的不同模板参数值,对`Base`类中的成员变量进行不同的初始化操作。请完成该C++代码的编写。
11.4万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
#include <iostream>

template <typename T, typename U>
class Base {
public:
    T t;
    U u;
    Base(T a, U b) : t(a), u(b) {}
    T func() {
        return t + u;
    }
};

template <typename T, typename U>
class Derived : public Base<T, U> {
public:
    Derived(T a, U b) : Base<T, U>(a, b) {
        // 根据不同模板参数值进行不同初始化操作
        if constexpr (std::is_same_v<T, int> && std::is_same_v<U, double>) {
            this->t = static_cast<T>(this->t * 2);
            this->u = static_cast<U>(this->u * 0.5);
        }
    }
    T func() override {
        return this->t * 2 * this->u;
    }
};

你可以使用以下方式测试这个代码:

int main() {
    Derived<int, double> d(3, 4.5);
    std::cout << "Derived func result: " << d.func() << std::endl;
    return 0;
}