一道c++笔试题
1 #include <vector> 2 3 struct Point { 4 Point(int xx, int yy) 5 : x(xx) 6 , y(yy) 7 {} 8 9 int const x; 10 int const y; 11 }; 12 13 int main() 14 { 15 std::vector<Point> pts; 16 pts.push_back(Point(0, 0)); 17 return 0; 18 }
编译出现下列错误:
14.cpp: 在成员函数‘Point& Point::operator=(const Point&)’中:
14.cpp:4:8:自‘void std::vector<_Tp, _Alloc>::_M_insert_aux(std::vector<_Tp, _Alloc>::iterator, const _Tp&) [with _Tp = Point, _Alloc = std::allocator<Point>, std::vector<_Tp, _Alloc>::iterator = __gnu_cxx::__normal_iterator<Point*, std::vector<Point> >, typename
std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer = Point*]’实例化
/usr/include/c++/4.6/bits/stl_vector.h:834:4:自‘void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = Point, _Alloc = std::allocator<Point>, std::vector<_Tp, _Alloc>::value_type = Point]’实例化
14.cpp:13:26:从此处实例化
14.cpp:4:8: 错误: non-static const member ‘const int Point::x’, can’t use default assignment operator
14.cpp:4:8: 错误: non-static const member ‘const int Point::y’, can’t use default assignment operator
In file included from /usr/include/c++/4.6/vector:70:0,
from 14.cpp:2:
/usr/include/c++/4.6/bits/vector.tcc: 在成员函数‘void std::vector<_Tp, _Alloc>::_M_insert_aux(std::vector<_Tp, _Alloc>::iterator, const _Tp&) [with _Tp = Point, _Alloc = std::allocator<Point>, std::vector<_Tp, _Alloc>::iterator = __gnu_cxx::__normal_iterator<Point*,
std::vector<Point> >, typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer = Point*]’中:
/usr/include/c++/4.6/bits/vector.tcc:314:4: 附注: 在这里第一次需要生成的方法‘Point& Point::operator=(const Point&)’
原因分析:
由于模板必须支持复制操作,但const限定的变量一旦绑定是不能够修改的