Home >Backend Development >C++ >How to Define a Private Static Constant `std::string` in C ?

How to Define a Private Static Constant `std::string` in C ?

Linda Hamilton
Linda HamiltonOriginal
2024-12-27 09:36:13257browse

How to Define a Private Static Constant `std::string` in C  ?

Defining a Static Data Member of Type const std::string

In C , defining a private static constant for a class can be challenging when using the standard const std::string type. The error messages encountered indicate that the method being used is not compliant with the ISO C standard.

To define a private literal constant without using a #define directive, consider the following two approaches:

Inline Variables (C 17 and later)

Since C 17, inline variables can be used to declare static data members with constant initializers. This is done by adding the inline keyword before the static declaration within the class definition:

class A {
private:
  inline static const std::string RECTANGLE = "rectangle";
};

Definition Outside Class Definition (Prior to C 17)

Prior to C 17, static members must be defined outside the class definition and initialized separately. The static declaration within the class definition is made without an initializer:

class A {
private:
  static const std::string RECTANGLE;
};

// In an implementation file
const std::string A::RECTANGLE = "rectangle";

Note that the syntax of directly initializing static members with non-integral types within class definitions is only allowed with integral and enum types.

The above is the detailed content of How to Define a Private Static Constant `std::string` in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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