Hi, I was wondering if someone could look at this person class I am working on. The first part is the class header with the constructors for the class. In the second part I am trying to write the code but when I declare the get_age and get_name objects I get an error that states --- declaration is incompatible with "std::string person::get_name() const" I get the same error for the get_age. Can someone help to explain to me what I am doing wrong? Thank YOU, C.D.

#ifndef Lab10

#define Lab10

#include <string>

using namespace std ;

class person

{

public:

    person()    ;

    person( string pname, int page ) ;

    string get_name() const ;

    int get_age() const ;

private:

    string name ;

    int age ;

} ;

#endif






#include "Lab10.h"

#include <iostream>

#include <string>

person :: person()

{ 

    int page = 0 ;

}

 void person :: get_name() // This is where the error is !!!!!!!!!!!!!!

{

    cout << "Please enter the name of the person ";

    getline(cin,name) ;

}

int person :: get_age()  // This is where the error is !!!!!!!!!!!!!!!

{

    cout << "Please enter the age of the person " ;

    cin >> age ;

    return age ;

}

Recommended Answers

All 4 Replies

The declaration of get_name says that the return type is string. The definition says that the return type is void.

I changed it to string but I still get the same error for get_name and get_age.

The declarations are marked as const, which is correct. However, your definitions (in cpp file) are not marked const, which makes the declarations incompatible with the definitions. You need to match them exactly:

Declarations:

string get_name() const ;
int get_age() const ;

Definitions:

string person :: get_name() const // <-- notice the 'const' here.
{
    return name;  //<-- notice, you cannot modify 'name' inside this function.
}

int person :: get_age() const // <-- notice the 'const' here.
{
    return age;  //<-- notice, you cannot modify 'age' inside this function.
}

When a function is marked as const, it means that within it, the data members of the object cannot be modified. This is why I removed your code that prompts the user to enter the name or age. You need to do those things in a separate set of functions:

Declarations:

void prompt_for_name();
void prompt_for_age();

Definitions:

void person :: prompt_for_name()
{
    cout << "Please enter the name of the person ";
    getline(cin,name) ;
}
void person :: prompt_for_age()
{
    cout << "Please enter the age of the person " ;
    cin >> age ;
}

That's pretty much it. Enjoy!

Thank you very much. I really apreciate the help, hopefully I will understand it all with patience and a little help from nice people like you.

Have a nice day, C.D.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.