问题描述
为什么返回对指向的成员变量的引用工作,而不是其他变量工作?我知道一个 const
成员函数应该只返回 const
引用,但为什么这不似乎真的指针? / p>
Why does returning the reference to a pointed-to member variable work, but not the other? I know that a const
member function should only return const
references, but why does that not seem true for pointers?
class MyClass
{
private:
int * a;
int b;
public:
MyClass() { a = new int; }
~MyClass() { delete a; }
int & geta(void) const { return *a; } // good?
int & getb(void) const { return b; } // obviously bad
};
int main(void)
{
MyClass m;
m.geta() = 5; //works????
m.getb() = 7; //doesn't compile
return 0;
}
推荐答案
int & geta(void) const { return *a; } // good?
int & getb(void) const { return b; } // obviously bad
在const函数中,每个数据成员变为const 无法修改的方式。 int
变为 const int
, int * $ c> int * const
,等等。
In a const-function, every data member becomes const in such way that it cannot be modified. int
becomes const int
, int *
becomes int * const
, and so on.
由于您的第一个函数中的 a
的类型变为 int * const
,而不是 const int *
,因此您可以更改数据(可修改):
Since the type of a
in your first function becomes int * const
, as opposed to const int *
, so you can change the data (which is modifiable):
m.geta() = 5; //works, as the data is modifiable
区别: const int *
和 int * const
。
-
const int *
表示指针为非常量,但指针指向的数据为 const 。 -
int * const
表示指针 const ,但指针指向的数据是 / strong>。
const int*
means the pointer is non-const, but the data the pointer points to is const.int * const
means the pointer is const, but the data the pointer points to is non-const.
您的第二个函数尝试返回 const int&
,因为 b
的类型变为 const int
。但是你在代码中提到了 int&
的实际返回类型,所以这个函数不甚至编译(参见),不管你在 main()
中做什么,因为返回类型不匹配。这里是修复:
Your second function tries to return const int &
, since the type of b
become const int
. But you've mentioned the actual return type in your code as int &
, so this function would not even compile (see this), irrespective of what you do in main()
, because the return type doesn't match. Here is the fix:
const int & getb(void) const { return b; }
现在。
这篇关于从const成员函数返回非const引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!