Could anyone please explain me why I get the following error?
A.cpp: In member function ‘void A::NewObject(int)’:
A.cpp:11: error: ‘list_a’ was not declared in this scope
I tried declaring list_a i various places. Now it is in prog.cpp, in main(). I don't get it why it isn't allegedly in the scope.
My simplified code is below. My idea was to add (NewObject) an object of a class A to a list (Add) while additionally performing some sort of a test (Compare) defined within the A class.
I am a C++ beginner so I'd especially appreciate detailed answers. Thanks in advance. Here are the files:
//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);
}
Well the answer is simple: you have never declared a variable named list_a in class A. Thats it.
Do it that way:
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);
};
Remove the U template parameter from your list class.
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".
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.