第29435题 单选题
针对如下C++模板结构体代码,下列说法正确的是?
#include <iostream>
#include <string>

template<typename T>
struct MyStruct {
    T val;
    MyStruct(T v) : val(v) {}
    T getVal() { return val; }
};

// 针对std::string的全特化版本
template<>
struct MyStruct<std::string> {
    std::string val;
    MyStruct(std::string v) : val("prefix_" + v) {}
    std::string getVal() { return val; }
};
A

MyStruct<int> s(10); std::cout << s.getVal(); 可正确编译运行,输出结果为10

B

MyStruct<std::string> s("test"); std::cout << s.getVal(); 可正确编译运行,输出结果为test

C

MyStruct s(3.14); 可直接正确编译,无需显式指定模板参数类型

D

MyStruct<const char*> s("hello"); 会触发std::string的特化版本,输出prefix_hello

程序运行统计
暂无判题统计
提交0次 正确率0.00%
答案解析