Home > Backend Development > C++ > How to implement generic classes in C++?

How to implement generic classes in C++?

王林
Release: 2024-06-06 13:13:57
Original
598 people have browsed it

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.

How to implement generic classes in C++?

How to implement generic classes in C++

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;
};
Copy after login

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”
Copy after login

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();
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template