【问题标题】:How to pass the address of private data through main() function?如何通过 main() 函数传递私有数据的地址?
【发布时间】:2015-07-24 21:06:40
【问题描述】:

逆序打印链表的元素

#include "stdafx.h"
#include<iostream>
#include<conio.h>
using namespace::std;
struct node
{
    int data;
    node* next;
};
class linklist
{
    node* head;
public:
    linklist()
    {
        head = NULL;
    }
    void create_list(int d);
    void reverse_print_list(node*);

}

void reverse_print_list(node* p)
{
    if (p == NULL)
        return;
    reverse_print_list(p->next);
    cout << endl << p->data << " ";
}

int main()
{
    linklist l1;
    l1.create_list(10);
    l1.create_list(20);
    l1.create_list(30);
    l1.create_list(40);
    l1.create_list(50);
    l1.print_list(& head);  // Not allowed , gives compilation error 
    _getch();
    return 0;
}

这里我要传递“head”的地址。但它不能在课堂外访问,因为它是私人数据
如何解决这个问题呢 ???

【问题讨论】:

  • 为什么要作为参数传递?列表本身知道头部是什么——它是它的成员。
  • @ molbdnilo :我其实很困惑,但我想通过 main() 函数。后来我想递归调用 print_list。

标签: c++ oop


【解决方案1】:

添加一个用head调用递归函数的公共重载:

void reverse_print_list() {reverse_print_list(head);}

现在可以将递归函数设为私有。

【讨论】:

  • 谢谢你的朋友。你的评论帮助了我。 :)
猜你喜欢
  • 2010-09-13
  • 2018-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-18
  • 1970-01-01
  • 1970-01-01
  • 2015-11-23
相关资源
最近更新 更多