类函数无法解析嵌套类实例或函数

问题描述 投票:1回答:2

我正在为Stack类编写成员函数。我有一个链接列表(LL)嵌套类作为Stack类的成员。在Stack构造函数中,我实例化了一个新的链接列表,该列表调用LL构造函数。使用LL的成员函数,我生成一个新节点并将其指向第一个堆栈。这可以解决。

但是,当我对Stack成员函数进行编码时,eclipse不再解析在Stack构造函数中生成的LL实例或Im试图调用的LL成员函数。

我已经尝试在PrivatePublic成员名称之间切换嵌套类。我还尝试通过使封闭类成为嵌套类的成员,像上一个问题/响应中那样,将嵌套类(LL)与它的封闭类/父类(Stack)连接起来:

Nested Class member function can't access function of enclosing class. Why?

都没有产生作用

这里没有问题:

class Stack
{
  private:
    int height, top_element;
    class LL
    {
      push_front(string * new_address)
      {
        ... ; // definition 
      }
     ... // more nested-class members
    };
  public:
    Stack(); // constructor
    void push(string); // enclosing class member
};

堆栈构造函数也很好:

Stack::Stack(int size)
{
    height = size;
    top_element = 0;

    string stack[height];

    LL stack_map;
    stack_map.push_front(stack);
}

当我到达这里时,我遇到了问题:

void Stack::push(string data)
{
    if (top_element == height - 1)
    {
        string stack[height];

        stack_map.push_front(stack); // <- PROBLEM
    }
}

我希望我不要包含太多代码。第二个步骤是演示构造函数实例化LL并调用push_front()没问题,而下一个定义则抱怨相同的函数并且无法识别实例化的LL,stack_map

[stack_mappush_front都用红色下划线

Symbol 'stack_map' could not be resolved

Method 'push_front' could not be resolved
c++ class inner-classes
2个回答
2
投票

您主要有两个问题!

  1. 您在LL的构造函数中有一个Stack类的对象类,在作用域内是本地的,在成员中不可用功能push

    您有

    LL stack_map;
    

    在类(即Stack::Stack(int size) {...}的构造函数的范围内,不在类void Stack::push(string data)的成员函数Stack中。

    因此,当您这样做时

       stack_map.push_front(stack);
    

    在成员函数(即Stack::push)中,编译器不知道,因此不知道错误。

    如果要访问LL类的同一对象(即stack_map)在Stack类的其他成员函数中,需要将其保留为该类的成员变量。

  2. 其次,variable length of arrays are not part of the standard C++。含义,stack

    的构造函数中的代码
    string stack[height];
    

    应更改。更好的替代方法是std::vector的] [std::vector

含义,更改为

std::string

1
投票

[第二个步骤是演示了构造函数实例化#include <vector> // std::vector class Stack { private: int height, top_element; class LL { public: void push_front(const std::vector<std::string>& new_address) { /* code here */ } // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^--->> vector of `std::string` }; LL stack_map; // >>>> `stack_map` member of `Stack` public: Stack(int size) : height{ size } , top_element{ 0 } { std::vector<std::string> stack(height); stack_map.push_front(stack); //>>>> push_back to the member `stack_map` } void push(const std::string& str) { if (top_element == height - 1) { std::vector<std::string> stack(height); stack_map.push_front(stack); //>>>> push_back to the member `stack_map` } } }; 并调用LL没问题,而下一个定义则抱怨相同的函数并且无法识别实例化的push_front()LL

您在onstructor中有一个名为stack_map的变量,但这只是一个函数局部变量。它不是该类的成员。因此,它在stack_map中不存在。

听起来像您需要使该类成为成员变量。

push()

完成之后,请确保从构造函数中删除函数局部变量。

© www.soinside.com 2019 - 2024. All rights reserved.