简体   繁体   中英

How to use Const Type Class in OOP C++?

Could you explain why I cannot use the const type in a class?

Example code:

class Array {
    int *Arr;
    int n;
public:
    Array(int _n = 0) {
        Arr = new int[_n];
        n = _n;
    }
    ~Array(void) {
        delete []Arr;
    }
    friend void f(const Array &A) {
        A.Arr[0] = 3;  // why can the Arr[0], Arr[1] be changed the value ?
        A.Arr[1] = 4;
    //  A.n = 10;        // can not be changed because of 'const class type'
    }
};

void main()
{
    Array A(5);
    f(A);
}

When I call f(A) , I have defined the const Array &A in f but the elements in void f() are also changeable, but when I try with the code line An = 10 , it is immutable.

Maybe I should define a const overloading operator or something in order to make all of the elements in Arr immutable.

Question: How can I make elements of Arr immutable?

Maybe i should define a 'const' overloading operator or something in order to make all of the elements in 'Arr' are immutable.

A.Arr[i] in your case is not immutable. A.Arr is.

You can not do the following:

A.Arr = newaddress;
++A.Arr; // etc

To overcome this problem, get rid of C style pointer (dynamic memory) and use:

int Arr[somesize];

or some container like std::array or std::vector to ensure your array is immutable.

Live demo of compilation failing with std::vector as container.

const Array &A means that the A object is to be treated as constant, so its members can't be modified; but other objects, such as those in the array that A.Arr points to, are not.

n = 10; is impossible not because A is const , but because a friend function is not a member, so there is no n . The const would prevent An = 10;

You could prevent modification of the array by only allowing access via member functions, not via the pointer:

public:
    Type       & operator[](size_t i)       {return Arr[i];}
    Type const & operator[](size_t i) const {return Arr[i];}

Now A[i] can only be used for modification if A is mutable.

Just to complete the answers, since your class is named Array , you should have overloaded the array subscript operator accordingly:

int &operator[](int index) { return Arr[index]; } // non-const overload

int operator[](int index) const { return Arr[index]; } // const overload

With that, you'll no longer have to mess with that friend function.

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