K
K
Ketchuuuup2020-05-28 12:35:36
C++ / C#
Ketchuuuup, 2020-05-28 12:35:36

Why can't I put the class in a separate file?

I can't use the methods that are in the human.cpp file, but from human.h I can.

When calling a method from human.cpp , the compiler says:
undefined reference to `human::human(std::string, int)'
undefined reference to `human::getAge()'

What am I doing wrong?

main.cpp

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

using namespace std;

int main ()
{
  human test("Bob", 54);
  cout << test.getAge() << endl;
  return 0;	
}


human.h
#ifndef HUMAN_H
#define HUMAN_H
#include <iostream>

using namespace std;

class human
{
  public:
    human (string newName, int newAge);
    void setName (string newName);
    void setAge (int newAge);
    string getName ();
    int getAge ();
  private:
    string name;
    int age;
};

#endif


human.cpp
#include "human.h"
#include <iostream>

using namespace std;

human::human (string newName, int newAge)
{
  setName(newName);
  setAge(newAge);
} 

void human::setName (string newName)
{
  name = newName;
}

void human::setAge (int newAge)
{
  age = newAge;
}

string human::getName ()
{
  return name;
}

int human::getAge ()
{
  return age;
}

int main ()
{
  return 0;
}


By the way, the compiler does not swear on human.cpp and human.h

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Ketchuuuup, 2020-05-28
@Ketchuup69

God, I'm ashamed...
There in main.cpp it was necessary to write this instead and remove the main function in the human.cpp file UPD: I worked in dev-c++ on windows 7. I didn't create a project. When I later decided to create a project, everything began to work for me. Thank you Anton Zhilin , I googled it and it’s really better not to include the .сpp file.
#include "human.h"
#include "human.cpp"
#include "human.h"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question