c++类中的函数模板获取该类的成员变量
时间: 2023-09-07 12:16:05 浏览: 505
在 C++ 类中,可以使用模板函数来获取类的成员变量。下面是一个示例代码:
class MyClass {
private:
int myVariable;
public:
template <typename T>
T GetVariable() {
return myVariable;
}
};
在上面的代码中,MyClass
类包含一个私有成员变量 myVariable
。GetVariable()
是一个模板函数,用于获取 MyClass
的成员变量。该模板函数可以返回不同类型的成员变量,因为它的返回类型是根据调用时提供的模板参数确定的。
你可以像这样调用 GetVariable()
函数来获取成员变量的值:
int main() {
MyClass obj;
obj.GetVariable<int>(); // 获取 int 类型的成员变量
obj.GetVariable<double>(); // 获取 double 类型的成员变量
return 0;
}
通过在模板函数中使用类型参数 T
,可以灵活地获取不同类型的成员变量。请根据你的实际需求调整代码。
希望这个示例能够帮助你!
相关推荐
















