Implementing generic classes in C++: using templates, specifying placeholders for types. Create an instance of a generic class, specifying type parameters. Generic classes allow the same code to be used for different data types. Practical application: Use the generic StudentArray class to store and process different types of data, such as student names.

Generic classes allow you to create code that can use different type of data. Here's how to implement a generic class in C++:
#include <iostream>
template <typename T>
class GenericClass {
public:
GenericClass(T value) : val(value) {}
void print() {
std::cout << "Value: " << val << std::endl;
}
private:
T val;
};In this example, GenericClass is a generic class and T is a placeholder for the type. You can create an instance of a generic class by specifying type parameters. For example:
GenericClass<int> intClass(10);
GenericClass<std::string> strClass("Hello");
intClass.print(); // 输出:“Value:10”
strClass.print(); // 输出:“Value:Hello”Practical case:
Consider an array containing student names. We can use generic classes to store and process different types of data, for example:
template <typename T>
class StudentArray {
public:
StudentArray(size_t size) : arr(new T[size]) {}
void add(T name, int index) {
arr[index] = name;
}
void print() {
for (size_t i = 0; i < size(); ++i) {
std::cout << "Student " << (i + 1) << ": " << arr[i] << std::endl;
}
}
size_t size() {
return size_;
}
private:
T* arr;
size_t size_;
};
int main() {
StudentArray<std::string> names(5);
names.add("John", 0);
names.add("Jane", 1);
names.add("Peter", 2);
names.add("Susan", 3);
names.add("Thomas", 4);
names.print();
}This code creates a generic array containing 5 strings. It has the ability to add and print student names.
The above is the detailed content of How to implement generic classes in C++?. For more information, please follow other related articles on the PHP Chinese website!
What are the differences between c++ and c language
Recommended learning order for c++ and python
Cost-effectiveness analysis of learning python and c++
Is c language the same as c++?
Which is better to learn first, c language or c++?
The difference and connection between c language and c++
C++ software Chinese change tutorial
Cost-effectiveness analysis of learning python, java and c++