简体   繁体   中英

c++ class constant of its own class

Basically, I would like to declare constants of a class within the class itself:

class MyClass {
    int itsValue;
    public:
        MyClass( int anInt) : itsValue( anInt) {}
        static const MyClass CLASSCONST;
};

So I can access it like this;

MyClass myVar = MyClass::CLASSCONST;

But I can't find a way to initialize MyClass::CLASSCONST. It should be initilized inside the MyClass declaration, but at that point the constructor is not known. Any one knowing the trick or is it impossible in c++.

class MyClass {
    int itsValue;
    public:
        MyClass( int anInt) : itsValue( anInt) {}
        static const MyClass CLASSCONST;
};

const MyClass MyClass::CLASSCONST(42);

Here is a working example with definition outside the class. The class declaration has a const static member which is initialized outside the class as it is a static member and of type non-integral. So initialization inside the class itself is not possible.

#include <iostream>

class test
{
    int member ;
public:
    test(int m) : member{m} {}

    const static test ob ;

    friend std::ostream& operator<<(std::ostream& o, const test& t)
    {
        o << t.member ;
        return o;
    }
};

const test test::ob{2};

int main()
{
    std::cout << test::ob ;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM