在这个函数中const函数:C++参考
(计数器是其中的函数operator ++声明类)
const Counter& operator++();
什么意思我函数常量?我不太了解const关键字与指针或引用的结合!
在这个函数中const函数:C++参考
(计数器是其中的函数operator ++声明类)
const Counter& operator++();
什么意思我函数常量?我不太了解const关键字与指针或引用的结合!
这意味着你可能不会使用这个引用来改变它所反对的对象。例如,如果你有型计数器
Counter obj1, obj2;
的两个对象便可不写
++obj1 = obj2;
因为由于限定符const的对象由操作者返回的参考refered至++是不可变的。
如果你想删除的操作符声明const限定符那么这种说法
++obj1 = obj2;
将是有效的。
实际上,声明preincrement运算符返回const引用并不是一个好主意。通常它宣称没有const限定符
Counter& opperator++();
在这种情况下,它的行为方式与前递增运算符++算术tyoes相同。例如,此代码有效
int x = 1;
++ x = 2;
并且结果是x = 2;
这是一个运算符重载,但声明语法与函数类似。你的声明可以分为3个部分:
const Counter&
operator++
()
(无参数)所以const Counter &
告诉您该函数将返回一个对Counter
对象的常量引用。一个常量引用使得对象不能被修改。
例如:
Counter c1;
++(++c1); // invalid
这里(++c1)
返回const reference
到Counter
对象。该引用增加,但是无效,因为该引用不能被修改(它是常量)。
您将preincrement运算符与postincrement运算符混淆后显示表达式计数器c1; (c1 ++)++; //无效 –
@VladfromMoscow ty,我的坏 – bolov
到这里说明我的意见的例子:
class xy
{
private:
int i; // const int i when object of xy is const
int *ptr; // int *const ptr when object of xy is const
public:
xy() : i(0), ptr(&i) { } // const i initialized to 0, only possible in constructor
// ptr pointing to i
void set (int s) { i=s; } // changes i, not possible to define this member function
// as const like read()
int read() const { return i; } // reads i
void ptr_set (int s) const { *ptr = s; }
};
int main()
{
const xy obj;
int read = obj.read(); // read() is allowed for const objects
obj.set(10); // not allowed! you could not define set() as const (like read()):
// there would be a compiler error, because this member function
// would try to change const i
obj.ptr_set(10); // allowed, would change i through pointer
return 0;
}
顺便说一句,任何人都可以解释为什么像obj.ptr_set(10)
毕竟是可能的const正确性的意义吗?
它返回“Counter”类型的常量引用。只有在函数出现在声明的末尾时,'const'才适用于该函数。如果它出现在声明的开头,它就适用于返回的类型。 –
但const使某些东西不能改变,现在我不能改变什么? –
[Const Correctness](http://www.parashift.com/c++-faq/const-correctness.html)。这将帮助你理解:) – demonking