0

谁能解释我为什么会收到以下错误?

A.cpp: In member function ‘void A::NewObject(int)’:
A.cpp:11: error: ‘list_a’ was not declared in this scope

我尝试在不同的地方声明 list_a。现在它在 prog.cpp 中,在 main() 中。我不明白为什么据称它不在范围内。

我的简化代码如下。我的想法是将(NewObject)类 A 的对象添加到列表(添加)中,同时另外执行在 A 类中定义的某种测试(比较)。

我是 C++ 初学者,所以我特别感谢详细的答案。提前致谢。以下是文件:

//A.h

#ifndef A_H
#define A_H

class A
{
private:
    int id;
    int Compare(int, int);
public:
    A()
    {
        id = 0;
    }
    A(int i)
    {
        id = i;
    }
    void NewObject(int i);
};
#endif

//A.cpp

#include "A.h"
#include "List.h"

void A::NewObject(int i)
{   
    list_a->Add(i);
}

int A::Compare(int a, int b)
{
    if ( a>b ) return 1;
    if ( a<b ) return -1;
    else return 0;
}


//List.h

#ifndef LIST_H
#define LIST_H

template<typename T>
class Node
{
public:
    T* dana;
    Node *nxt, *pre;
    Node()
    {
        nxt = pre = 0;
    }
    Node(const T el, Node *n = 0, Node *p = 0 )
    {
        dana = el; nxt = n; pre = p;
    }
};

template<typename T, typename U>
class List
{
public:
    List()
    {
        head = tail = 0;
    }
    void Add(const U);
protected:
    Node<T> *head,*tail;
};

#endif


//List.cpp

#include <iostream>
#include "List.h"

template<typename T, typename U>
void List<T,U>::Add(const U el)
{
    int i = 5;
    Node<T> *hlp = new Node<T>();
    head = hlp;
    if ( Compare(el,i) > i )
        std::cout << "Ok" << std::endl;
}

//prog.cpp
#include "List.h"
#include "A.h"

int main()
{
    int i = 5;
    List<class A, int> *list_a = new List<class A, int>();
    A obj;

    obj.NewObject(i);
}
4

2 回答 2

1

答案很简单:您从未在 A 类中声明过名为 list_a 的变量。就是这样。

这样做:

class A
{
private:
    List <int> list_a;
    int id;
    int Compare(int, int);
public:
    A()
    {
        id = 0;
    }
    A(int i)
    {
        id = i;
    }
    void NewObject(int i);
};

从列表类中删除 U 模板参数。

于 2012-04-21T23:52:36.453 回答
-1

When this type of error occurs, there might be a mismatch of class name in the main function. Check whether they are same. Only then, you will get an error like not declared in this scope, which means "they are not declared properly".

于 2019-12-02T16:27:26.740 回答