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
Release: 2024-12-27 09:36:13
Original
253 people have browsed it

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

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template