简体   繁体   中英

Error creating a class object

I am having a problem creating a simple class object. I created a small program to simulate the problem. I have a class "Person" with data members string name , string eye_color , and int pets . When I call Person new_person("Bob", "Blue", 3) , my debugger shows this as the new_person 's value:

{name=""eye_color=""pets=-858993460}

I'm looking at previous projects where I had no problems with this and am not spotting anything...What am I missing?

person.h

#include <iostream>
#include <string>

class Person
{
public:
    Person(std::string name, std::string eye_color, int pets);
    ~Person();

    std::string name;
    std::string eye_color;
    int pets;
};

person.cpp

#include "person.h"

Person::Person(std::string name, std::string eye_color, int pets)
{
    this->name;
    this->eye_color;
    this->pets;
}
Person::~Person(){}

city.h

#include "person.h"

class City
{
public:
    City();
    ~City();

    void addPerson();
};

city.cpp

#include "city.h"

City::City(){}
City::~City(){}

void City::addPerson(){
    Person new_person("Bob", "Blue", 3);
}

main.cpp

#include "city.h"

int main(){
    City myCity;

    myCity.addPerson();
}

It doesn't look like you are actually assigning the values in the Person class so that is why you are getting random values for those data members.

It should be:

Person::Person(std::string name, std::string eye_color, int pets)
{
    this->name = name;
    this->eye_color = eye_color;
    this->pets = pets;
}

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