Home > Backend Development > C++ > Why Do Static Const Integer Members Require Separate Definitions in C ?

Why Do Static Const Integer Members Require Separate Definitions in C ?

Susan Sarandon
Release: 2024-12-10 07:12:10
Original
791 people have browsed it

Why Do Static Const Integer Members Require Separate Definitions in C  ?

Defining Static Const Integer Members in Class Definition

Contrary to popular belief, initializing a static const integral in the class definition isn't sufficient to generate the necessary definition required by other code. As witnessed by the compilation error reported by the provided code, a separate definition is still mandatory:

#include <algorithm>
#include <iostream>

class test
{
public:
    static const int N = 10;
};

int main()
{
    std::cout << test::N << "\n";
    std::min(9, test::N); // Error: Undefined reference to `test::N'
}
Copy after login

This problem stems from std::min's parameter taking mechanism: it captures values by const reference. If it took by value, no separate definition would be needed.

Workaround

Though defining the static const member outside the class fixes the issue, there's a better solution: using the constexpr keyword. This eliminates the need for a separate definition and handles other edge cases.

class test
{
public:
    static constexpr int N = 10;
};
Copy after login

The above is the detailed content of Why Do Static Const Integer Members Require Separate Definitions 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