关于const函数的一个疑问?解决方法
关于const函数的一个疑问?
下面这段程序,为什么红色语句不会报错,而蓝色语句会报错!!!!
------解决方案--------------------
const 放函数后面这个只有对类成员函数才可以。
------解决方案--------------------
const 放函数后面这个只有对类成员函数才可以。
下面这段程序,为什么红色语句不会报错,而蓝色语句会报错!!!!
- C/C++ code
#include <iostream.h> const int Test1() { return 1; } int Test2() const { return 1; } int main() { int x1,x2; [color=#FF0000]x1 = Test1();[/color] [color=#0000FF]x2 = Test2();[/color] return 0; }
------解决方案--------------------
const 放函数后面这个只有对类成员函数才可以。
------解决方案--------------------
const 放函数后面这个只有对类成员函数才可以。
- C/C++ code
const int Test1() { return 1; } class C { public: int Test2() const { return 1; } }; int main() { int x1, x2; C c; x1 = Test1(); x2 = c.Test2(); return 0; }
------解决方案--------------------
如果不放到类中还是会报错的,和调不调用x2 = Test2()无关
- C/C++ code
#include <iostream.h> const int Test1() { return 1; } int Test2() const //这里还是会报错的,和调不调用x2 = Test2()无关 { return 1; } int main() { return 0; }
------解决方案--------------------
1.const int Test1()
对返回值加const没有任何意义
2.int Test2() const
对非成员函数无效,对成员函数的意义其实是这样的:
int Test2(const this);