只是一点警告:我现在只做C ++ 2周了,期待看到愚蠢的初学者错误。
我正在编写一些(无用的)代码来熟悉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
我做过研究,显然这个错误是由复制构造函数执行非const操作引起的。我得到了那么多。作为回应,我使CValue :: getData()成为const成员。除了访问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 ++书籍才能正常使用。
答案 0 :(得分:6)
而不是
const string getData();
试
string getData() const;
您的版本使返回字符串为const,而不是方法。
答案 1 :(得分:4)
你需要使getData
成为const方法:
const string CValue::getData() const {
return *value;
}
此外,正如您的班级现在所看到的,没有必要使value
成为指针。只需将其作为成员对象即可。