const关键字在C++中,我有一些麻烦了解其中使用const,这3种方式的区别:差异在C++
int get() const {return x;}
const int& get() {return x;}
const int& get() const {return x;}
我想有例子来帮助我明白了一个明确的解释差异。
const关键字在C++中,我有一些麻烦了解其中使用const,这3种方式的区别:差异在C++
int get() const {return x;}
const int& get() {return x;}
const int& get() const {return x;}
我想有例子来帮助我明白了一个明确的解释差异。
这里是最const
例如:
class Foo
{
const int * const get() const {return 0;}
\_______/ \___/ \___/
| | ^-this means that the function can be called on a const object
| ^-this means that the pointer that is returned is const itself
^-this means that the pointer returned points to a const int
};
你的具体情况
//returns some integer by copy; can be called on a const object:
int get() const {return x;}
//returns a const reference to some integer, can be called on non-cost objects:
const int& get() {return x;}
//returns a const reference to some integer, can be called on a const object:
const int& get() const {return x;}
This question介绍一点关于const
成员函数。
Const参考也可以用于prolong the lifetime of temporaries。
不错的答案,但我会扩大一点关于const成员函数的部分。它可以在const对象上调用,是的,但是我会补充说它是一个承诺,不会更改任何成员变量,也不会调用任何非const成员函数,并且此承诺由编译器执行,如果违反,会发生错误。 –
谢谢@SingerOfTheFall,我知道这是一个基本问题,但在我看来并不十分清楚 – Kruncho
(1) int get() const {return x;}
这里我们有两种优点,
1. const and non-const class object can call this function.
const A obj1;
A obj1;
obj1.get();
obj2.get();
2. this function will not modify the member variables for the class
class A
{
public:
int a;
A()
{
a=0;
}
int get() const
{
a=20; // error: increment of data-member 'A::a' in read-only structure
return x;
}
}
虽然由常数函数改变类[A]的成员变量,编译器会引发错误。
(2) const int& get() {return x;}
将指针返回到常量整数引用。
(3)const int& get() const {return x;}
它是组合答案(2)和(3)。
它已经在每个基本的C++教科书中得到很好的解释。 –