Understanding Undefined References to Static Members
When working with classes containing static data members, you may encounter errors related to "undefined references." This can be attributed to a lack of clear understanding regarding declarations and definitions.
Declarations and Definitions
In a class declaration, static data members are typically declared but not defined. This declaration establishes the member's existence and type. However, unless it's used in a way that requires an address, a specific definition is not yet necessary.
To provide a definition for a static data member, it should be placed in a separate source file that contains the implementation for the class. The definition consists of the member's name, preceded by the class :: scope operator, followed by an optional initializer.
Exception for Constants
For static members that are const integral or enumeration types, an initializer can be provided within the class declaration. This does not negate the need for a definition in the source file, but it ensures that the definition does not contain an initializer.
Templates
Static data members of class templates are defined differently. The definition is included in the header file alongside the class declaration. This exception to the One Definition Rule allows for the static member to be defined once for each instantiation of the template.
Other Uses of static
Beyond static data members, static can also be applied to functions and objects in a non-class context, where it denotes different meanings:
By understanding these concepts, you can effectively handle static data members in C and avoid errors related to undefined references.
The above is the detailed content of Why Do I Get \'Undefined References\' to Static Members in C ?. For more information, please follow other related articles on the PHP Chinese website!