C++ 将"this"指针用作普通指针
C++ Using the "this" pointer as a normal pointer
我目前正在尝试使用"this"指针传递一个指针到一个函数:
void GameObject::process_events()
{
std::vector<ObjectEvent*>::iterator it;
for (it = events.begin(); it != events.end(); it++)
(*it)->process(this);
}
Class ObjectEvent
{
private:
bool* trigger;
void (*response)(GameObject*);
public:
process(GameObject* obj)
{
if (*trigger)
response(obj);
}
};
但是我得到一个错误:
No matching function call to 'ObjectEvent::process(GameObject* const)'
有什么问题吗?
根据您的错误消息判断,process_events()似乎实际上是一个const函数。
void GameObject::process_events() const
{
process(this);
}
如果是,则this
是const指针,process()必须接受const GameObject *
。否则process()可能会修改传递给它的点,这违反了process_events不修改this
的承诺。
void process(const GameObject* obj);
或者,从process_events()中删除const修饰符。
如果您从this
中返回this
的成员函数是const,那么它将是一个const指针。如果成员函数没有声明为const,指针也不会声明为
void GameObject::process_events()
{
// ...
process(this); // 'this' is NOT a const pointer
}
void GameObject::process_events() const
{
// ...
process(this); // 'this' IS a const pointer
}
相关文章:
- 为什么使用 "this" 指针调用派生成员函数?
- 关于C++中具有多重继承"this"指针的说明
- Doees the 'this' 指针参与虚函数的多态行为
- 指针'this+1' C++中指的是什么?
- 为什么使用指向函数的指针调用虚函数时不需要指针"this"?
- Lambda 函数捕获错误的指针"this"
- 调用类的方法时,类的指针"this"变为 null C++
- 指针'this'可以是共享指针吗?
- 如何在C++中为指针'this'赋值
- C++:指针"this"没用吗?
- 指针"this"有什么问题?
- 将指针'this'传递为 LPARAM
- 错误 C2663:指针'this'重载没有合法转换
- C++ : 了解指针"this"
- 更改对象的指针'this'以指向不同的对象
- C++编译器是为所有成员方法生成指针"this"还是仅为引用成员的方法生成指针?
- 使用指针和不使用指针"this"有区别吗?
- 将enable_shared_from_这个基于类的指针(this)存储在itelf中
- 创建指向对象的指针"this"
- 如何在类中取消初始化指针"this"?