为什么我在编译时会收到一个关于丢弃代码中限定符的g++错误
Why am I getting a g++ error about discarding qualifiers in my code when compiling?
只是一个小小的警告:我现在才做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
设为指针。只需将其作为成员对象即可。
相关文章:
- 如何修复我的最大公约数代码?它适用于除零和零以外的所有数字
- 如何在Qt 4.8中阻止/忽略/丢弃早于特定超时的用户输入事件
- 请找出我的代码中的错误,它在提交得到错误答案的同时仍然适用于我的所有测试用例
- 代码适用于调试,但不适用于发布
- 如何析构单例实例,或者为什么以下代码适用于析构函数?
- std::sort / 适用于测试代码,但无法推断出模板
- 代码似乎不适用于较大的输入,但适用于较小的输入
- 我的代码仅适用于一个输入.请指教
- 如果 LTO 中的代码依赖于其构造的副作用,是否允许 LTO 删除未使用的全局对象?
- C++实现代码中的字符串不应存在于输出二进制文件中.如何解决
- 动态强制转换适用于模板成员函数内的共享指针和弱指针,无需代码重复
- 我需要转换一些代码,以便它适用于输入和输出文件文本
- 代码具有特定于函数的变量,用于更改范围之外的值
- Lambda 表达式等效于 C++ 代码
- GPU cuda 代码是否适用于多个 GPU 卡而无需任何实现
- 分割故障(代码丢弃)
- 计算 c# 中二进制文件符号的频率不起作用,但适用于等效的 c++ 代码
- 设置精度应用于旧的 C 样式代码
- C++等效于下面的代码(SprintF)
- 我是否可以在类似于 C# 的 C++ 中创建全局命名空间层次结构,以帮助开发人员使用我们的代码?