常量成员函数
关于常量成员函数,个人理解为在对应的类中不能够改变该类的数据成员,那么常量成员函数在实际的应用中有何作用呢?
[解决办法]
作用你自己不是已经说出来嘛。
[解决办法]
为了让程序好看一点!
[解决办法]
举个例子
void fun(const A& ma)
{
ma.functoin(...);//这个时候只能调用const成员函数
}
const的意思你都知道,而类中有const就是提供给const的对象来调用的
[解决办法]
const成员函数是保证只访问const成员的吧,并没有说是必须const对象来调用啊
[解决办法]
简单地说,楼主不是不理解什么叫常量成员函数,而是不理解常量这个东西的作用
常量用来保证程序员不会在编程的时候修改一些原本不希望修改的东西,是用来限制程序员的
在编译后的代码里,不存在所谓的常量——当然,有时编译器优化会直接把常量替换成初始化数据嵌入到代码里了。但原理上,常量不过是“数据不会改变的变量”。在编译后,常量和变量都是同等的内存地址,没有任何区别。
常量成员函数的作用,就在于防止程序员在编写这个函数的时候不小心改变了某个成员变量。编译后,常量成员函数和非常量成员函数没有任何区别,都只是代码空间的代码段而已。
[解决办法]
防止错误,有时候你思路清晰但也会写出诡异的代码,算是手误把。这时候编译器会帮你把关。同时更加清晰,对于可改的可不改的(mutable),在设计类的时候就让你去思考这个问题。这是对你负责也是对代码负责!
[解决办法]
class A{public: void f1() {} void f2() const {}};int wmain(){ const A a; a.f1(); // error a.f2(); // ok return 0;}
[解决办法]
#include <iostream>using namespace std;class TestConst{public: int function()const; int function2(); TestConst(int val, int const1):num(val), constant(const1){}private: int num; const int constant;};//Declaring a member function with the const keyword specifies that// the function is a "read-only" function that does not modify the //object for which it is called.int TestConst::function()const//const方法,返回普通变量{ //function2();//error //A constant member function cannot modify any data members or call any member //functions that aren't constant. return num;}int TestConst::function2()//普通函数返回const变量{ return constant;}int main(){ TestConst myConstant(10, 20); const TestConst yourConstant(1000, 2000); cout<<myConstant.function()<<endl;//非const对象调用const方法 cout<<myConstant.function2()<<endl;//非const对象调用非const方法 cout<<yourConstant.function()<<endl;//const对象调用const方法 //cout<<yourConstant.function2()<<endl;//const对象调用非const方法,错误 return 0;}
[解决办法]