#include <iostream>
class MyClass {
public:
void print() const {
std::cout << "This is a const method." << std::endl;
}
void modify() {
std::cout << "This is a non-const method." << std::endl;
}
};
int main() {
const MyClass obj;
// 使用 const_cast 移除 const 属性
MyClass* nonConstObj = const_cast<MyClass*>(&obj);
// 调用非 const 成员函数
nonConstObj->modify(); // 注意:修改 const 对象的非 const 成员函数是未定义行为
return 0;
}
const
或 volatile
属性。obj
是一个 const
对象,意味着它的成员函数只能是 const
成员函数。const_cast
可以将 const
对象转换为非 const
对象,从而允许调用非 const
成员函数。const_cast
允许这样做,但修改 const
对象的非 const
成员函数会导致未定义行为(Undefined Behavior),因此在实际编程中应尽量避免这样做。上一篇:c++创建数组
下一篇:c++map的使用
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站