const vector implies const elements?

后端 未结 4 957
难免孤独
难免孤独 2021-02-05 00:11
4条回答
  •  猫巷女王i
    2021-02-05 00:27

    So a const object can only call const methods. That is:

    class V {
      public:
        void foo() { ... }        // Can't be called
        void bar() const  { ... } // Can be called
    };
    

    So let's look at a vector's operator[]:

    reference       operator[]( size_type pos );
    const_reference operator[]( size_type pos ) const;
    

    So when the vector object is const, it will return a const_reference.

    About: (*v[0]).set(1234);

    Let's break this down:

    A * const & ptr = v[0];
    A & val = *ptr;
    val.set(1234);
    

    Note that you have a constant pointer to variable data. So you can't change what is pointed at, but you can change the value that the pointer points at.

提交回复
热议问题