0
任何人都可以请解释我为什么会出现以下错误?C++错误:未在此范围内声明的对象
A.cpp: In member function ‘void A::NewObject(int)’:
A.cpp:11: error: ‘list_a’ was not declared in this scope
我试过声明list_a我在各个地方。现在它在main.c中的prog.cpp中。我不明白为什么它不在范围内。
我的简体代码如下。我的想法是添加(NewObject)类A的对象到列表(Add),同时另外执行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);
}
我不得不仔细检查一下。 – chris 2012-04-21 23:54:11
是的,它在main()的范围内。第11行的范围是该函数的本地范围;函数不共享局部变量。请记住,main()是一个函数,就像其他任何函数一样,它只是第一个叫 – 2012-04-21 23:55:08
现在它在prog.cpp中,在main()中。但我试过在A.cpp中声明,但它也不起作用。它应该是什么样子,我应该把它放在哪里? – 2012-04-21 23:55:35