const vector隐含const元素吗? [英] const vector implies const elements?
问题描述
const向量< A>
是否也意味着其元素也是 const
?
Does const vector<A>
mean that its elements are const
as well?
在下面的代码中,
v [0] .set(1234);
在 void g(const vector< A& v)
中产生编译器错误
v[0].set (1234);
in void g ( const vector<A> & v )
produces the compiler error
const.cpp:28:3:错误:成员函数'set'不可行:'this'
参数具有
type'const value_type'(aka'const A' ),但函数未标记为const
const.cpp:28:3: error: member function 'set' not viable: 'this' argument has type 'const value_type' (aka 'const A'), but function is not marked const
为什么?
但是(* v [0])。set(1234);
在 void h(const vector< A *>& v)$ c中$ c>
对于编译器是可以的。
But (*v[0]).set(1234);
in void h ( const vector<A *> & v )
is OK for the compiler.
版本之间有什么区别?
// ...........................................................
class A {
private:
int a;
public:
A (int a_) : a (a_) { }
int get () const { return a; }
void set (int a_) { a = a_; }
};
// ...........................................................
void g ( const vector<A> & v ) {
cout << v[0].get();
v[0].set (1234);
} // ()
// ...........................................................
void h ( const vector<A *> & v ) {
cout << (*v[0]).get();
(*v[0]).set(1234);
} // ()
推荐答案
第一个版本
v[0].set (1234);
无法编译,因为它试图更改通过引用返回的向量的第一个元素。编译器认为这是一个更改,因为 set(int)
未标记为 const
。
does not compile because it tries to change the vector's first element returned to it by reference. The compiler thinks it's a change because set(int)
is not marked const
.
另一方面,第二个版本仅从向量读取
The second version, on the other hand, only reads from the vector
(*v[0]).set(1234);
并根据结果调用 set
在a上调用 v [0]
时,将取消对常量引用的引用。 const
向量,您将获得对 A
的 const
引用。 。如果元素类型是指针,则在其上调用 set
即可。您可以将第二个示例更改为
When you call v[0]
on a const
vector, you get back a const
reference to A
. When element type is a pointer, calling set
on it is OK. You could change the second example to
v[0]->set(1234);
并获得与以前相同的结果。这是因为您获得了对常量的引用,但是该指针所指向的项目不是常量。
and get the same result as before. This is because you get a reference to a pointer that is constant, but the item pointed to by that pointer is not constant.
这篇关于const vector隐含const元素吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!