如何在 C++ 中从类成员函数自己的定义递归调用该函数
How to call a class member function recursively from its own defintion in C++?
我是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:
会有什么区别吗?
不,不会有。可以从另一个成员函数调用类的任何成员函数。
- 这个C++编译器优化(在自身的实例上调用对象自己的构造函数)的名称是什么,它是如何工作的?
- 是否可以在不填充自己的参数的情况下将模板函数作为参数传递?
- 在C++中,我可以在定义自己的复制构造函数后跳过定义赋值运算符吗?
- 在类自己的成员函数中构造类时,如何强制类模板参数推导?
- 在这种情况下,工会成员会调用自己的析构函数吗
- 您自己的类型的结构化绑定,不是结构或元组(通过公共成员函数)
- 我正在尝试在视觉工作室上创建自己的库/源函数
- 将自己的函数添加到 ifstream
- 在函数调用时C++多组参数及其自己的括号?
- 如何解决对自己的C++成员函数的未定义引用?
- C :基类调用自己的虚拟函数 - 一个反图案
- 自己的C++列表类实现(插入函数)出现问题
- 函数可以将指针返回其自己的类型
- 类中的枚举在调用自己的函数时不会改变
- GCC 或 Clang 关于函数参数在其自己的默认参数中的范围内的名称是否正确?
- 如何自己为我自己的shared_ptr实现实现别名构造函数
- 如何在我自己的类 Vector 中使用 Move 构造函数而不是 Move 赋值运算符
- G++ 切换为不包含自己的符号函数名称(和调试数据)-
- 在构造函数(C )中填写我自己的向量类
- 如何在 C++ 中从类成员函数自己的定义递归调用该函数