【问题标题】:Unable to correctly access my class declared inside the private area of another class无法正确访问在另一个类的私有区域内声明的我的类
【发布时间】:2026-01-30 06:55:02
【问题描述】:

我目前正在为我的队列类开发一个深拷贝构造函数,但我对正确访问封装在私有区域中的数据的技术有点坚持。

queue.h 文件

class Queue
{
  public:
   Queue( const Queue& q );
   // other functions I have not yet finished yet, but will soon!

 private:
 class node  // node type for the linked list 
{
   public:
       node(int new_data, node * next_node ){
          data = new_data ;
          next = next_node ;
       }
       int data ;
       node * next ;
};

node * front_p ; 

node * back_p ;

int current_size ; 
};

这是我的以下包含函数的 queue.cpp 文件(实现)

#include "queue.h"
#include <cstdlib>

Queue::Queue(const Queue& q ) // not sure
{

    if (front_p == NULL && back_p == NULL){
        front_p = back_p -> node(q.data, NULL); // problem here ;(
    }
        while (q != NULL)
        {
            node *ptr = new node;
            ptr->node(q.data, NULL)
            //ptr->data = q.data;
            back_p->next = ptr;
            back_p = ptr;
            q=q.next;
        }
        current_size = q.current_size;
}

*请注意,我的 main.cpp 不包括在内,因此没有 int main 以防某些人认为 queue.cpp 是主文件。它是queue.h的实现

所以为了解释我的代码应该做什么,我将一个 Queue 类的实例传递给复制构造函数,并且我想访问 q 中的数据。我曾尝试使用 q.data,但效果不佳,我意识到我试图访问的“数据”在另一个类中。

当然,我想也许我应该尝试做类似 q.node.data 的事情,但这只是一厢情愿。

我的以下错误是从终端复制到这里的:

queue.cpp:14:23: error: invalid use of ‘Queue::node::node’
   front_p = back_p -> node(q.data, NULL);
                   ^
queue.cpp:14:30: error: ‘const class Queue’ has no member named ‘data’
   front_p = back_p -> node(q.data, NULL);

【问题讨论】:

    标签: c++ queue copy-constructor deep-copy


    【解决方案1】:

    您遇到问题的整个代码块毫无意义。

    if (front_p == NULL && back_p == NULL){
        // stuff
    }
    

    这是一个构造函数。 front_pback_p 没有预先存在的值。所以if 没用。 this 对象此时始终为空。

    front_p = back_p -> node(q.data, NULL); // problem here ;(
    

    从代码的角度来看,该行毫无意义。 back_p 未设置,因此在其上使用 -&gt; 运算符是非常错误的。目前尚不清楚您甚至在这里尝试做什么。你是说

    front_p = back_p = new node(q.front_p->data, NULL);
    

    但是如果q.front_p 为NULL(另一个队列为空)怎么办?

    你的问题还在继续

    while (q != NULL)
    

    q 不是可以为 NULL 的指针。大概你想遍历q中包含的项目列表,从q-&gt;front_p开始。

    【讨论】:

    • 谢谢!这确实为我解决了很多问题,还有一些我没有想到的问题。我意识到我的代码中有很多多余的东西哈哈....