string.cpp: In function ‘int const_f(const string&)’:
string.cpp:6:4: error: passing ‘const string’ {aka ‘const std::__cxx11::basic_string’} as ‘this’ argument discards qualifiers [-fpermissive]
a=“abc”;
^~~~~
const string a= “abc”;
a=“abc”;
这个错误的解释是:传递一个‘const string’ 作为this参数,将导致舍弃限定符。也就是 const string里只有一个限定词 const,就会导致舍弃const。为什么会提示这个错误呢?
这个错误比较难理解的是这个 'this’参数;错误里为什么会专门提示这个this参数;这个就需要往后看,最后这一行会被翻译成一个赋值构造函数,而类里对于成员函数,就是通过这个隐式的参数作为修改对象的一个管道,this是一个隐藏的参数。而这个赋值构造的参数是一个非const this参数,所以才会出现这个错误。
In file included from /usr/include/c++/8/string:52,
from /usr/include/c++/8/bits/locale_classes.h:40,
from /usr/include/c++/8/bits/ios_base.h:41,
from /usr/include/c++/8/ios:42,
from /usr/include/c++/8/ostream:38,
from /usr/include/c++/8/iostream:39,
from string.cpp:1:
/usr/include/c++/8/bits/basic_string.h:707:7: note: in call to ‘std::__cxx11::basic_string<_CharT, _Traits, _Alloc>& std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::operator=(const _CharT*) [with _CharT = char; _Traits = std::char_traits; _Alloc = std::allocator]’
operator=(const _CharT* __s)
^~~~~~~~