C++ 编译器如何检测非常量函数体?
How can a C++ compiler detect a non-const function body?
无意中发现了以下代码:
class Person
{
private:
char name[10];
public:
// this won't compile:
char* getName_1() const {
return name;
}
// this will:
const char* getName_2() const {
return name;
}
};
我想知道编译器究竟如何判断 getName_1()
不是 const 函数。因为函数体内并没有真正修改成员变量的代码。
由于 getName_1
被标记为 const
class 的所有字段都被视为常量。
因此 getName_1
中 name
的类型是 const char[10]
。
无法隐式转换为char *
(return类型),编译报错
getName_1()
是 const 方法,因为它在其声明中字面上标记为 const
。这意味着它的隐式 this
指针是 const
,因此 name
成员被视为 const
,因此 getName_1()
不能 return non-const 指向 const 数据的指针,这就是它无法编译的原因。
作为对其他(正确)答案的补充,编译:
class Person
{
private:
char* name;
public:
// this compiles:
char* getName_1() const {
return name;
}
};
最重要的是,这表明与流行的神话相反,C++ 中的数组不是指针。
无意中发现了以下代码:
class Person
{
private:
char name[10];
public:
// this won't compile:
char* getName_1() const {
return name;
}
// this will:
const char* getName_2() const {
return name;
}
};
我想知道编译器究竟如何判断 getName_1()
不是 const 函数。因为函数体内并没有真正修改成员变量的代码。
由于 getName_1
被标记为 const
class 的所有字段都被视为常量。
因此 getName_1
中 name
的类型是 const char[10]
。
无法隐式转换为char *
(return类型),编译报错
getName_1()
是 const 方法,因为它在其声明中字面上标记为 const
。这意味着它的隐式 this
指针是 const
,因此 name
成员被视为 const
,因此 getName_1()
不能 return non-const 指向 const 数据的指针,这就是它无法编译的原因。
作为对其他(正确)答案的补充,编译:
class Person
{
private:
char* name;
public:
// this compiles:
char* getName_1() const {
return name;
}
};
最重要的是,这表明与流行的神话相反,C++ 中的数组不是指针。