同一成员函数是否可以为该类的不同对象具有不同的定义?
重要提示:我无法使用this solution中的回调。 (原因在下面的示例中说明)
让我们说我们有这个对象:
struct object
{
int n;
int m;
void f();
};
是否可能有类似的东西:
object a,b;
// and here to define the functions
a.f() {std::cout << n+m;}
b.f() {std::cout << n-m;}
我不能使用回调的原因是因为我要定义的函数将是递归的并且将溢出。我要使用此方法进行的操作是创建堆栈的模拟(但所有变量都以双链列表存储在堆上),因此我将调用没有局部变量的void (void)
函数增加该功能可以实现的堆栈深度。还要提及的重要一点是,我想用这个想法制作一个头文件。对于进一步的上下文解释,这是它的工作方式:
MyHeader.h
template <typename PARAM_TYPE> class HEAP_FUNCTION
{
private:
struct THIS_CALL // ! THIS HAS NOTHING TO DO WITH THE __thiscall CALLING CONVENTION !
{
PARAM_TYPE* PARAM;
THIS_CALL* next_call;
THIS_CALL* prev_call;
};
THIS_CALL* FIRST_CALL;
THIS_CALL* CURRENT_CALL;
public:
HEAP_FUNCTION(PARAM_TYPE* FirstCall)
{
FIRST_CALL = new THIS_CALL;
CURRENT_CALL = FIRST_CALL;
FIRST_CALL->PARAM = *FirstCall;
}
HEAP_FUNCTION(PARAM_TYPE FirstCall)
{
FIRST_CALL = new THIS_CALL;
CURRENT_CALL = FIRST_CALL;
FIRST_CALL->PARAM = FirstCall;
}
~HEAP_FUNCTION()
{
delete FIRST_CALL;
}
void call(void);
};
Source.cpp
// This is the ilustration of the recursive method for calculating
// the 1+2+3+...+n sum.
// The "normal" definition for this function would be:
//
// unsigned long long sum(unsigned long long n)
// {
// if (n == 0) return 0;
// return n + sum(n-1);
// }
//
// The function presented bellow is the equivalent.
struct Param
{
unsigned long long n;
unsigned long long return_value;
}
int main()
{
Param start_value;
start_value.n = 10; // we will calculate 1+2+...+10
HEAP_FUNCTION<Param> Gauss(&start_value);
// We imagine this is where i define call().
// The code written in this definiton works correctly.
Gauss.call()
{
// Test if the function needs to stop further calls.
if(CURRENT_CALL->PARAM->n == 0)
{
CURRENT_CALL->PARAM->return_value = 0;
return;
}
// Prepare the parameters for the next function call.
CURRENT_CALL->next_call = new THIS_CALL;
CURRENT_cALL->next_call->PARAM = new PARAM_TYPE;
CURRENT_CALL->next_call->prev_call = CURRENT_CALL;
CURRENT_CALL->next_call->PARAM->n = CURRENT_CALL->PARAM->n - 1;
// Call the next instance of the function.
CURRENT_CALL = CURRENT_CALL->next_call;
call();
CURRENT_CALL = CURRENT_CALL->prev_call;
// Collect the return value of the callee.
CURRENT_CALL->PARAM->return_value = CURRENT_CALL->PARAM->n + CURRENT_CALL->next_call->PARAM->return_value;
// Delete the space used by the callee.
delete CURRENT_CALL->next_call;
}
// This is the actual call of the function.
Gauss.call();
// The return value is found in the start_value struct.
std::cout << start_value.return_value << std::endl;
return 0;
}
重要提示:派生整个类将为call()
和sum(a, b)
之类的功能产生一个单独的dif(a, b)
定义,因为它们将使用相同的{{ 1}}结构。 (即使它们不是递归的,并且有人使用它的可能性很小,但是当您的某些函数具有很多参数并将其放在堆上会导致更多的堆栈时,此方法在较大的程序中很好用空格)
答案 0 :(得分:0)
不认为我对问题的理解正确,但是您是否考虑过函数重载?