如何在 C++ 中从类成员函数自己的定义递归调用该函数

How to call a class member function recursively from its own defintion in C++?

本文关键字:函数 自己的 定义 递归 调用 成员 C++      更新时间:2023-10-16

我是C++新手,我需要一个类成员函数来从它自己的定义调用自己,像这样 -

class MyClass {
public:  // or private: ?
    // Some code here
    // ...
    void myfunction();
    // ...
};
void MyClass::myfunction()
{
    // Some code here
    // ...
    // Call MyClass::myfunction() here, but how?    
    // ...
}

但我不知道它的正确语法,以及如何在不创建通常像这样这样做的对象的情况下自行调用它 - 如果可能的话object_name.member_function()

而且,如果myfunction()属于public:private:,会有什么区别吗?

由于该函数不是静态的,因此您已经有一个实例可以操作

void MyClass::myfunction()
{
    // Some code here
    // ...
    this->myfunction();
    // ...
}

你可以把this->关掉,我只是更清楚如何调用该函数。

myfunction()在类的范围内,所以你可以"简单地"调用它:

class MyClass {
public:
    // Some code here
    // ...
    void myfunction();
    // ...
};
void MyClass::myfunction()
{
    myfunction();
}

但是请注意,这将导致堆栈溢出。您需要一种停止递归的方法。

成员函数实际上是句法糖的一种形式。它们描述了一个函数,该函数以某种方式秘密地获取指向对象实例的指针,该对象实例在函数内部可作为this访问。

struct Foo {
    vod bar();
};
Foo foo;
foo.bar();

你在这里的通话中真正要做的是调用Foo::bar(&foo);,而bar实际上是在Foo* this指针。如何完成因实现而异,一些编译器/架构将使用特殊的寄存器来跟踪当前对象。

额外的语法糖使成员函数中的所有成员变量和函数对您可见,就好像它们是局部作用域一样

struct Foo {
    int i;
    int add(int n) {
        return i + n;
    }
    int addx2(int n) {
        return add(n) * 2;
    }
};

这里实际发生的事情是:

return this->i + n;

return this->add(n) * 2;

这意味着很容易遇到本地名称和成员名称之间存在冲突的情况。

struct Foo {
    int i;
    Foo(int i) {
        i = i; // not what you expected
    }
};

出于这个原因,许多工程师会仔细使用大小写、前缀或后缀来帮助他们区分成员、参数和变量。

struct Foo { // Uppercase for types and functions
    int m_i;  // m_ for member
    Foo(int i_, int j_) {
        int i = sqrt(i));
        m_i = i + j_;
    }
    int Add(int i) {
        return i_ + i;
    }
};

人们使用各种不同的模式 - 有些人使用_name来表示成员,有些人使用name_fn_来表示成员。

struct Foo {
    int i_;
    int add_(int _i) {
        return i_ + _i;
    }
};

最主要的是保持一致。

但我不知道它的正确语法,如果不创建通常这样做的对象,如何自行调用它 - 如果可能的话object_name.member_function()

用:

void MyClass::myfunction()
{
    // Some code here
    // ...
    // Call MyClass::myfunction() here, but how?
    // One way to call the function again.
    this->myfunction();
    // ...
}

this->mufunction()可以替换为myfunction()。使用this是一种风格选择,它使某些人(如我)更容易阅读代码。

而且,myfunction()属于public:private:会有什么区别吗?

不,不会有。可以从另一个成员函数调用类的任何成员函数。