简体   繁体   中英

C++ class member initialization & constructor definition

Hello I started learning C++ and at the moment i'm testing member initializers I have written this simple code:

#include <iostream>
#include <string>

using namespace std;

class Person
{
public:
    Person();
    ~Person();
private:

    string p_name;
    string p_surname;
    int p_age;

};

Person::Person(string name, string surname, int age) : p_name(name), p_surname(surname), p_age(age)
{


}

Person::~Person()
{
}

class MyClass
{
public:
    MyClass(int value) : m_value(value)
    {
    }
private:
    int m_value;
};

int main()
{
    return 0;
}

However in Person class I get the following error

Error 1 error C2511: 'Person::Person(std::string,std::string,int)' : overloaded member function not found in 'Person' c:\\users\\syd\\documents\\visual studio 2013\\projects\\consoleapplication1\\consoleapplication1\\consoleapplication1.cpp 19 1 ConsoleApplication1

Also in the second class there is no error. If I'm not mistaken I'm declaring the constructor in the wrong way in Person class and the interpreter thinks I'm overloading a missing method? I'm sure an error like this might be silly to most of you but if someone could explain in simple terms what I'm doing wrong I would be grateful.

The declaration of Person() does not match the definition of Person(string name, string surname, int age) .

In your class declaration, change person to

public:
  Person(string name, string surname, int age);

You need to put a prototype of your constructor (the one with parameters) in the class Person instead of the current prototype which has no parameters

class Person
{
public:
    Person(string name, string surname, int age);
    ~Person();
private:

    string p_name;
    string p_surname;
    int p_age;

};

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM