What is the point of a non-static data member const?

For the following code:

class A
{
public:
    const int cx = 5;
};

Here, an instance of cx will be created for each object A. This seems unnecessary to me, since cx can never be modified. In fact, I see no reason why the compiler should not force a const element to be created. Can anyone explain this to me?

+4
source share
4 answers

The const data element does not have to be the same for all instances. You can initialize it in the constructor.

class A
{
public:
    A(int n) :cx(n) {}

    const int cx;
};

int main()
{
    A a1(10);
    A a2(100);
}
+8
source

Actually, I see no reason why the compiler should not have a static data element static.

, cx , , A?
const , , , .

, :

struct Multiplier
{
    const int factor;

    Multiplier(int factor) : factor(factor) {}

    int operator()( int val ) const
    {
        return val * factor;
    }
};

std::vector<int> vec{1, 2, 3};
std::vector<int> vec2;

int i;
std::cin >> i;

std::transform( std::begin(vec), std::end(vec),
                std::back_inserter(vec2), Multiplier(i) );

// vec2 contains multiples of the values of vec
+6

, , , , . ; - :

class Matrix
{
    const int myRowCount;
    const int myColumnCount;
    std::vector<double> myData;
    //  ...
public:
    Matrix( int rows, int columns )
        : myRowCount( rows )
        , myColumnCount( columns )
        , myData( rows * columns )
    {
    }
    //  ...
};

const , . ( , . .)

+1

const.

, Employee. -, , . Employee e1 e2, e1 = e2 . , . , , , .

, . , , , Employee. ; , , - . dob - , . ,

0

All Articles