C++ 重新定义特定对象的类方法
C++ Redefining Class Method for Specific Objects
我有一个类foo
,它有一个方法doesSomething()
.我构造了该类的多个对象,但对于一些特定的对象,我希望doesSomething()
做其他事情。构造后如何动态地重新定义该方法的主体?
我相信这正是我正在寻找的,但它是用Java的。
如果要"覆盖"以前的类定义,可以使用虚函数,并使用派生类。
这里有一些例子,特别是在"虚拟成员"标题下。
祝你好运。
struct nasty_object {
nasty_object()
: _something_do { std::bind(&nasty_object::normal_thing, this) }
{
}
void normal_thing() {
// the stuff to do in the default case
}
void do_other_thing() {
// the stuff to do in the alternate case
}
void do_something() {
if(_something_do) {
_something_do();
}
}
// replace the meaning of 'do_something()'
void set_do_something(std::function<void()> f)
{
_something_do(std::move(f));
}
private:
std::function<void()> _something_do;
};
现在您可以在运行时创建对象并更改 do_something() 的含义,如下所示
auto n1 = nasty_object{};
auto n2 = nasty_object{};
auto n3 = nasty_object{};
n2.set_do_something(std::bind(&nasty_object::do_other_thing, &n2));
n3.set_do_something([&n3] {
// do something totally different!
});
n1.do_something(); // does something
n2.do_something(); // does the other thing
n3.do_something(); // does whatever was in your lambda
注意:仅仅因为您可以使用 c++ 执行此操作并不意味着您应该这样做。这种不负责任的行为最好留给剧本骑师和其他人,没有任何好处。
在C++中,对象没有对方法的引用,它们具有对"虚拟函数表"又名"类"的引用。 因此,您需要让另一个类参与进来,以您设想的方式进行操作。但是你也说你想在对象被构造后改变它 - 这意味着你不能使用虚函数来做到这一点。相反,您应该使用函数指针,甚至只是一个简单的布尔值:
class C {
bool isSpecial;
void doesSomethingNormal() { ... }
void doesSomethingSpecial() { ... }
void doesSomething() {
if (isSpecial)
doesSomethingSpecial();
else doesSomethingNormal();
}
};
相关文章:
- 从父类方法返回子类对象
- 根据对象类调用不同的方法
- 对类中的对象使用方法
- 使用基类对象访问派生的仅类方法
- 如何调用其对象位于函数内的类方法
- 根据 C++ 中的属性对对象类进行分区的优化方法
- 在DelphiInterface上实现Dynamic_cast以获取基础对象类的任何方法
- 将 std::ofstream 对象作为参数传递给类方法
- 我是否要创建一个对象来使用C 中的类方法
- 如何将对象类的方法传递为 std::function?
- 调用不访问已删除对象中的任何类成员的类方法是否安全
- 如何找到C 向量中存储的对象的类方法
- 调用对象类方法,该方法在另一个对象类中的向量中
- 从返回基类指针的派生类对象调用方法
- C - 函数能够访问类方法,而不会创建静态或对象
- 为什么可以从实例化基类对象的投射指针调用非静态派生类方法
- 如何在.dll类方法参数中传递对象
- 如何创建新类以部署opencv和对象的方法
- 对基类方法slice对象的c++调用
- 无法创建对象并使用其模板类方法