gpt4 book ai didi

c++ - 为什么我在编译时会收到有关在代码中丢弃限定符的 g++ 错误?

转载 作者:太空狗 更新时间:2023-10-29 23:42:00 26 4
gpt4 key购买 nike

只是一个小警告:我现在只用了 2 周的时间来学习 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;

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

关于c++ - 为什么我在编译时会收到有关在代码中丢弃限定符的 g++ 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6547041/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com