【发布时间】:2026-02-08 00:05:01
【问题描述】:
#include<string>
#include<iostream>
using namespace std;
template<class T>
class Student_Grades
{
string name;
int NoExams;
T *grades_ptr;
static int counter;
public:
Student_Grades(string n, int no)
{
name=n;
NoExams=no;
grades_ptr=new T[no];
counter++;
}
void Print()
{
cout<<"Name: "<<name<<endl;
cout<<"NoExams: "<<NoExams<<endl;
for(int i=0; i<NoExams; i++)
{
cout<<"Grade "<<i+1<<": "<<grades_ptr[i]<<endl;
}
cout<<endl<<endl;
}
void set_grade(int index, T grade)
{
grades_ptr[index]=grade;
}
T get_grade(int index)
{
return grades_ptr[index];
}
int get_counter()
{
return counter;
}
~Student_Grades()
{
delete[] grades_ptr;
counter--;
}
};
此代码将为每个模板特化创建不同的计数器。 如何使计数器全局化,这意味着每次创建对象时它都会递增?在 Main 中,我创建了 3 个 Student_Grades 对象,其中一个具有 int 特化。一个是双精度的,一个是字符的。计数器给我 1。我如何让它给我 3?
【问题讨论】:
-
你根本不使用静态成员变量,而是使用全局变量。
-
把它放在模板外面。例如。在一个共同的基类中。
-
是的,我只是想了一下。非常基本,对不起:) 和谢谢
标签: c++ class templates static template-specialization