https://m.toutiao.com/is/inHnMVR/?=
#暑期创作大赛#
#include <stdio.h> int main() { const int x = 5; x = 10; // 编译错误,尝试修改只读变量 printf('%d\n', x); return 0;}
在上面代码中,变量x被声明为只读(不可修改)的常量,因此尝试对其进行赋值操作会导致编译错误。
#include <iostream>class MyClass {public: void doSomething() { std::cout << 'Do something.' << std::endl; } void printData() const { std::cout << m_data << std::endl; }private: int m_data = 5;};int main() { const int x = 5; // C++中声明只读变量 // x = 10; // 编译错误,尝试修改只读变量 MyClass obj; obj.doSomething(); // 调用非只读成员函数 const MyClass& constObj = obj; constObj.doSomething(); // 可以调用只读成员函数 // constObj.m_data = 10; // 编译错误,尝试修改只读成员变量 constObj.printData(); // 可以调用只读成员函数 return 0;}
联系客服