将指针作为私有数据成员传递到 Main 中的成员函数中
Passing a pointer as a private data member into a member function in Main
我正在为学校解决一个问题,我正在对存储在线性链表中的值求和。
我有一个定义节点的结构。它有一个数据部分和一个指向 next 的指针。
我有一个类,该类具有在公共部分中处理列表的函数,在私有部分中具有一个名为head
的指针。
我在实现文件中实现了一个递归函数来对值求和。 它以node*
为论据。
我的问题是,如果它是私有数据成员,如何将该head
指针传递到main()
中的函数中?
我已经成功地迭代实现了这一点,所以请假设该列表在 main()
中成功实例化。我只是不知道如何将指针从那里传递到我的函数中。
你不把它传进去。该类已经拥有它。如果可以的话,你的班级应该是这样的:
class Foo {
node* _head;
node* _tail;
public:
Foo() : _head(nullptr), _tail(nullptr) {}
~Foo() {
while(_head != nullptr) {
node* temp = _head;
_head = _head->next;
delete temp;
}
}
void insert(const int arg) {
if(_head = _nullptr) {
_head = new node(arg);
_tail = _head;
} else {
_tail->next = new node(arg);
_tail = _tail->next;
}
}
int sum() const {
int total = 0;
for(auto i = _head; i != nullptr; i = i->next) {
total += i->val;
}
return total;
}
};
请注意,sum
不需要将_head
传递给它,因为_head
实际上已经是sum
作为方法的对象的成员。
相关文章:
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- "main"函数堆栈中的对象在第一个任务运行时被覆盖 (FreeRTOS)
- 为什么 'main' 函数中的局部 int 变量会自动初始化?
- 为什么在我的 main 函数中声明整数后我的整数数组中会出现错误?
- 尝试更改 main 函数内的全局变量值时出现编译错误 C++.
- 我应该在 main 函数中写什么来测试我的问题?
- 如何在 main 函数中输出两个新字符串C++?
- 有没有办法通过 main 函数访问受保护的矢量大小而无需将其转换为公共?
- 我们可以在main函数中声明嵌套类对象吗
- 为什么Main函数上的Sleep()会停止所有线程
- C++ main 函数中初始化静态变量
- 为什么VC++/MFC没有main函数?
- 如何在 main 函数的一个对象中初始化两个类的值?C++
- 在 C++ 中解析 main 函数的大量输入的正确方法是什么
- 如何编写一个 void 函数,该函数将在数组中搜索值,并通过引用将该值的位置传递回 main 函数
- 如何将矩阵参数发送到从C 中的MAIN函数
- 如何从子例程函数获取到 main 函数的返回值
- 为什么我不能在 main 函数中更改类的公共变量
- C++编译错误:多个定义"main",但项目中只有一个 main 函数
- 如何使用 x86 程序集在 c 中访问 main 函数中的变量