Const Data Member Initialization in C
In C , when attempting to initialize a const data member within a class declaration, errors such as "ISO C forbids initialization of member" and "making 't' static" may arise. To resolve this, it's essential to understand the nature of const data members.
Const variables indicate a value that cannot be modified during program execution. However, C mandates that object definitions have unique declarations. To adhere to this rule, const variables cannot be defined within class declarations.
The solution lies in defining the const variable outside the class declaration, using the initializer list. The syntax for initializing a const data member is:
className() : memberName(value) {}
In your example:
#include <iostream> using namespace std; class T1 { const int t; public: T1() : t(100) {} }; int main() { T1 obj; cout << "T1 constructor: " << obj.t << endl; return 0; }
This code initializes the const data member t with the value 100 during object construction, avoiding the aforementioned errors.
The above is the detailed content of How to Properly Initialize Const Data Members in C ?. For more information, please follow other related articles on the PHP Chinese website!