【发布时间】:2012-03-14 20:20:49
【问题描述】:
我必须在两个软件之间架起某种桥梁,但我遇到了一个我不知道如何处理的问题。希望有人会提出有趣且(最好)可行的建议。
这是背景:我有一个 C++ 软件套件。我必须用另一个函数替换给定类中的某些函数,这没关系。问题是新函数调用另一个函数,该函数必须是静态的,但必须处理类的成员。这是让我抓狂的第二个功能。
如果函数不是静态的,我会收到以下错误:
error: argument of type ‘void (MyClass::)(…)’ does not match ‘void (*)(…)’
如果我将其设置为静态,我会收到以下错误:
error: cannot call member function ‘void
MyClass::MyFunction(const double *)’ without object
或
error: ‘this’ is unavailable for static member functions
取决于我是否使用“this”关键字(“Function()”或“this->Function()”)。
最后,类对象需要一些我无法传递给静态函数的参数(我无法修改静态函数原型),这会阻止我在静态函数本身内创建新实例。
您将如何以最少的重写来处理这种情况?
编辑:好的,这是我必须做的简化示例,希望它是清晰和正确的:
// This function is called by another class on an instance of MyClass
MyClass::BigFunction()
{
…
// Call of a function from an external piece of code,
// which prototype I cannot change
XFunction(fcn, some more args);
…
}
// This function has to be static and I cannot change its prototype,
// for it to be passed to XFunction. XFunction makes iterations on it
// changing parameters (likelihood maximization) which do not appear
// on this sample
void MyClass::fcn(some args, typeN& result)
{
// doesn't work because fcn is static
result = SomeComputation();
// doesn't work, for the same reason
result = this->SomeComputation();
// doesn't work either, because MyClass has many parameters
// which have to be set
MyClass *tmp = new MyClass();
result = tmp->SomeComputation();
}
【问题讨论】:
-
静态函数显然无法访问(非静态)成员变量。我不确定你的第一次和最后一次尝试是什么。你能显示相关代码吗?
-
发布包含静态函数声明和定义的代码。否则很难理解所问的内容。静态函数没有
this指针,所以你不能做this->。您需要将它应该处理的对象作为参数传递给函数。 -
this 在静态上下文中无效,因为没有类实例。
-
代码很复杂,所以我没有贴出来,我会尝试写一些在“代码模式”下说明问题的东西(不知道需要多长时间)。
-
@SkippyleGrandGourou 由于您无法更改函数原型,因此您必须在调用函数之前使用全局指针或静态成员变量,将其设置为指向
this。但是,如果您有多个类的实例,这将无法正常工作。看我的回答。