在函数参数列表中使用const关键字可以表明函数不会修改传入的参数值。 void MyFunction(const int x) { // x不可被修改 } ``` 6. 修饰函数返回值 可以使用const来修饰函数的返回值,表示返回的值不可被修改。 const int MyFunction() { return 42; } ``` 7. 修饰类的成员函数 在类的成员函数中使用...
示例如下:Plain Text复制代码9912345678910cppCopy codevoid func(int x) {cout << "Value: " << x << endl;}int main() {void (*const ptr)(int) = func; // 指向常量的函数指针,不能修改指针指向的函数ptr(5); // 调用函数// ptr = nullptr; // 错误,不能修改指针return 0;}...
voidfunction(constintVar);//传递过来的参数在函数内不可以改变(无意义,因为Var本身就是形参) voidfunction(constchar*Var);//参数指针所指内容为常量不可变 voidfunction(char*constVar);//参数指针本身为常量不可变(也无意义, 因为char* Var也是形参) 参数为引用,为了增加效率同时防止修改。 修饰引用参数时: vo...
1。const 只能声名 member function 2。const member function 不能修改对象的任意成员 3。const member function 不能调用非 const member function ——— int a = 1; int* const p = &a; //常量指针 p指向的地址不能改变,但p指向的地址里面的值是可以改变的。 比如*p = 2,这样a的值1就改变成2了。...
C:/Users/XXX/CLionProjects/untitled1/main.cpp:39:34: error: cannot convert 'std::_Bind_helper<false, void (IoMgr::*)(int, std::vector<int>&), const IoMgr*, const std::_Placeholder<1>&, const std::_Placeholder<2>&>::type' to 'MsgCallBack' {aka 'std::function<void(int, std...
C:\Users\Windows\CLionProjects\Project1\main.cpp: In function 'int main()': C:\Users\Windows\CLionProjects\Project1\main.cpp:10:22: error: passing 'const Time' as 'this' argument discards qualifiers [-fpermissive] t1.set_time(2,2,2); ...
// constant_member_function.cpp class Date { public: Date( int mn, int dy, int yr ); int getMonth() const; // A read-only function void setMonth( int mn ); // A write function; can't be const private: int month; }; int Date::getMonth() const { return month; // Doesn't...
// constant_member_function.cppclassDate{public: Date(intmn,intdy,intyr );intgetMonth()const;// A read-only functionvoidsetMonth(intmn );// A write function; can't be constprivate:intmonth; };intDate::getMonth()const{returnmonth;// Doesn't modify anything}voidDate::setMonth(intmn )...
test.cpp: In function ‘intmain()’: test.cpp:8: 错误:assignment of read-only variable ‘a’ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. const int * const a; 这个就是定死了,a也不能修改,(*a)也不能修改,而且a必须初始化。
2.》》const与指针和引用。(a)const与指针。先来看看下面的几种定义:intme;constint*p1=&me;//p1可变,*p1不可变,此时不能用*p1来修改,但是p1可以转向 int*constp2=&me;//p2不可变,*p2可变,此时允许*p2来修改其值,但是p2不能转向。constint*constp3=&me;//p3不可变,*p3也不可变...