When is a non-static const data member more useful than a const static one?

前端 未结 2 1427
一个人的身影
一个人的身影 2021-01-21 03:49

In C++ there are static and non-static const data members. When I want a constant, I always make it static because it does not make sense to have multi

相关标签:
2条回答
  • 2021-01-21 04:17
    class MyClass
    {
        public:
           MyClass(int val): myVal(val) {}
           const int myVal;
    };
    

    In this small example, myVal is readable by everyone without a getter method, but it's not modifiable as soon as MyClass is instantiated.

    You just declare data types as const if you want to make sure they are not modified later on.

    Because myVal is not static, it can have different values for every different instance of MyClass. If myVal would be static, it would have the same value for every instance and would not be assignable by the constructor.

    Take the following example

    #include <iostream>
    using namespace std;
    
    class MyClass
    {
        public:
            MyClass(int val) : myConst(val) {}
            void printVars() {
                cout << "myStatic " << myStatic << endl;
                cout << "myConst " << myConst << endl;
            }
    
            static const int myStatic;
            const int myConst;
    };
    
    const int MyClass::myStatic = 5; //Note how this works without 
                                     //an instance of MyClass
    
    int main()
    {
        MyClass ca(23);
        MyClass cb(42);
        cout << "ca: " << endl;
        ca.printVars();
        cout << "cb: " << endl;
        cb.printVars();
        return 0;
    }
    

    Results:

    ca: 
    myStatic 5
    myConst 23
    cb: 
    myStatic 5
    myConst 42
    

    The following would result in a compilation error because the variables are const:

    ca.myConst = 11;
    ca.myStatic = 13;
    
    0 讨论(0)
  • 2021-01-21 04:18
    1. A static const applies to the class
    2. A const applies to the object

    E.g.

    class Verticies {
        public:
           const int colour;
           static const int MAX_VERTICIES = 100;
           Point points[MAX_VERTICIES];
           Verticies(int c) : colour(c) { }
           // Etc
    };
    

    Here MAX_VERTICIES applies to all objects of type Verticies. But different objects could have different colours and that colour is fixed on construction

    0 讨论(0)
提交回复
热议问题