为什么我在编译时会收到一个关于丢弃代码中限定符的g++错误

Why am I getting a g++ error about discarding qualifiers in my code when compiling?

本文关键字:代码 于丢弃 错误 g++ 一个 编译 为什么      更新时间:2023-10-16

只是一个小小的警告:我现在才做C++两周,预计会看到愚蠢的初学者错误。

我写了一些(无用的(代码来熟悉C++中的类(它是一个字符串的包装器(,并添加了一个复制构造函数,但我一直收到这个错误:

pelsen@remus:~/Dropbox/Code/C++/class-exploration> make val
g++ -o val.o val.cpp
val.cpp: In copy constructor ‘CValue::CValue(const CValue&)’:
val.cpp:27: error: passing ‘const CValue’ as ‘this’ argument of ‘const std::string CValue::getData()’ discards qualifiers
make: *** [val] Error 1

我做过研究,显然这个错误是由复制构造函数执行非常量操作引起的。我得到那么多。作为回应,我将CValue::getData((作为常量成员。除了访问getData((,复制构造函数什么都不做,所以我不明白为什么我仍然会得到错误。以下是(一些(错误代码:

  7 class CValue {
  8   string *value;
  9 public:
 10   CValue();
 11   CValue(string);
 12   CValue(const CValue& other);
 13   ~CValue();
 14   void setData(string);
 15   const string getData();
 16 };
 17 
 22 CValue::CValue(string data) {
 23   value = new string(data);
 24 }
 25 
 26 CValue::CValue(const CValue& other) {
 27   value = new string(other.getData());
 28 }
 37 
 38 const string CValue::getData() {
 39   return(*value);
 40 }

有人知道我做错了什么吗?因为我不知道。提前谢谢,我想我要买一本合适的C++书来开始正确的学习。

而不是

const string getData();

尝试

string getData() const;

您的版本使返回字符串为const,而不是方法。

您需要使getData成为常量方法:

 const string CValue::getData() const {
     return *value;
 }

此外,正如您的类现在所看到的,没有必要将value设为指针。只需将其作为成员对象即可。