gpt4 book ai didi

c++ - 如何在 C++ 类模板中使用静态变量

转载 作者:太空狗 更新时间:2023-10-29 20:55:29 25 4
gpt4 key购买 nike

这是从 geeksforgeeks 获取的示例。我不明白下面的代码。

template<class T> int Test<T>::count = 0;

count是外部变量吗?为什么不直接让 static int count = 0 呢?下面列出geeksforgeeks中的描述和代码。

Class templates and static variables: The rule for class templates is same as function templates Each instantiation of class template has its own copy of member static variables. For example, in the following program there are two instances Test and Test. So two copies of static variable count exist.

#include <iostream>

using namespace std;

template <class T> class Test
{
private:
T val;
public:
static int count;
Test()
{
count++;
}
// some other stuff in class
};

template<class T>
int Test<T>::count = 0;

int main()
{
Test<int> a; // value of count for Test<int> is 1 now
Test<int> b; // value of count for Test<int> is 2 now
Test<double> c; // value of count for Test<double> is 1 now
cout << Test<int>::count << endl; // prints 2
cout << Test<double>::count << endl; //prints 1

getchar();
return 0;
}

最佳答案

每次您使用新类型实例化测试对象时,都会为您创建一个来自可用模板的新类。 (因此,在您的情况下,编译器会根据需要为您创建 Test<int>Test<double> 类)。你现在可以想到Test<int>Test<double>作为从同一模板创建的 2 个独立类。

因为有两个类,所以在不同的作用域中有两份同名的静态变量。 template<class T> int Test<T>::count = 0;是定义此 count 的模板在按需创建的类(class)中。

如果您将此定义专门用于某种类型,例如:

template<>
int Test<int>::count = 5;

Test<int>::count将是 7在打印它的时候。同时 Test<double>::count将保留 1 (不变)。

关于c++ - 如何在 C++ 类模板中使用静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35594127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com