Reputation: 1
I'm having a problem when using the class files and the compiler error says "error: 'x' was not declared on this code" while it points out the cout, string, and endl. I have already wrote "#include " and "#include " in both header, class, and main file.
(Sorry for my English) I'm just a beginner and I wanted to know the basics
Added #include and #include in both files
//Main File (main.cpp)
#include <iostream>
#include "test.h"
#include <string>
using namespace std;
int main()
{
test *person = new person("Phroton",14)
person.Display();
return 0;
}
//test.h
#ifndef TEST_H
#define TEST_H
#include <iostream>
#include <string>
class test
{
private:
string name;
int age;
public:
void Display(){
cout << "I'm " << name << " and I'm " << age << "years old" << endl;
}
};
#endif // TEST_H
//test.cpp (There is no problem with this file at all)
#include "test.h"
#include <iostream>
#include <string>
test::test(string iname, int iage)
{
name = new string;
age = new int;
*name = iname;
*age = iage;
}
test::~test()
{
delete name;
delete age;
cout << "Info Deleted" << endl;
}
Upvotes: 0
Views: 1375
Reputation: 26800
Answering the specific problem you have asked:
This is because you have not specified the namespace cout
and endl
belong to in the file test.h
.
The statement in Display
should be:
std::cout << "I'm " << name << " and I'm " << age << "years old" << std::endl;
The alternative to this is the using namespace std
declaration but this is considered a bad practice (especially in a header file).
Note:
You do not need using namespace std
in main.cpp
as you are not using any functions from the std
namespace there. Even if you do, use the std::name
instead of the using
declaration.
Member function definitions are usually present in .cpp
files. So you can define the function Display
to test.cpp
.
Also consider moving away from raw pointers to smart pointers.
Upvotes: 0