【发布时间】:2011-02-17 23:05:02
【问题描述】:
我编写了以下代码来测试 const 成员函数: 当我有数据成员的 const 限定符时,它编译并运行良好 char *data 和构造函数的参数。但是,如果我从中删除 const 数据成员和构造函数,我得到编译器错误。 是不是因为字符串 "Hello World" 的类型总是 const char * ?
#include <iostream>
#include <string.h>
using namespace std;
class mystring {
const char *data;
mutable int length;
mutable int valid;
public:
mystring(const char *str) {data = str;}
~mystring() { };
int GetLength() const;
};
int mystring::GetLength() const
{
if (valid)
return length;
else {
length = strlen(data);
valid = 1;
return length;
}
}
int main()
{
const char *str = "Hello World";
mystring s(str);
cout << s.GetLength() << endl;
}
【问题讨论】:
-
去掉const限定的时候,是不是也把
main中str的声明去掉了? -
最初我将 str 声明为 mystring s = "Hello World";
-
mystring s = "Hello World"将与您的代码完美编译,即使您删除const如您在问题中描述的那样。此外,当您遇到“编译器错误”问题时,您必须发布您遇到的确切错误。这里没有人是心灵感应的。