Home > Backend Development > C++ > How to Properly Initialize Static Variables in C Classes?

How to Properly Initialize Static Variables in C Classes?

DDD
Release: 2024-12-05 13:12:11
Original
935 people have browsed it

How to Properly Initialize Static Variables in C   Classes?

Initialising Static Variables in C Classes

In object-oriented programming, it's often necessary to initialise static variables within classes. However, this practice can present challenges, as exemplified by the following question:

Dilemma:
A developer has identified several functions within their class that do not require object access and have therefore been marked as static. However, the compiler demands that all accessed variables also be declared static. The developer subsequently declares these variables as static const within the class but encounters compilation errors.

Solution:
To initialise static variables within a class, one should define them within the class declaration but initialise them in a separate source file. This is demonstrated below:

// Class Header
class Thing {
public:
    static string RE_ANY;
    static string RE_ANY_RELUCTANT;
};

// Source File
string Thing::RE_ANY = "([^\n]*)";
string Thing::RE_ANY_RELUCTANT = "([^\n]*?)";
Copy after login

Alternative Consideration:
It's important to note that making functions static means they are no longer associated with an object and cannot access non-static members. Instead, consider marking them as const, which prevents them from modifying members but allows access to them.

The above is the detailed content of How to Properly Initialize Static Variables in C Classes?. For more information, please follow other related articles on the PHP Chinese website!

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