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