创建类对象时出错

Error creating a class object

本文关键字:出错 对象 创建      更新时间:2023-10-16

我在创建一个简单的类对象时遇到问题。我创建了一个小程序来模拟这个问题。我有一个包含数据成员的类"人"string namestring eye_colorint pets。当我调用Person new_person("Bob", "Blue", 3)时,我的调试器将其显示为new_person的值:

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

正在查看以前的项目,我对此没有任何问题,也没有发现任何东西......我错过了什么?

人.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;
};

人.cpp

#include "person.h"
Person::Person(std::string name, std::string eye_color, int pets)
{
    this->name;
    this->eye_color;
    this->pets;
}
Person::~Person(){}

城市.h

#include "person.h"
class City
{
public:
    City();
    ~City();
    void addPerson();
};

城市.cpp

#include "city.h"
City::City(){}
City::~City(){}
void City::addPerson(){
    Person new_person("Bob", "Blue", 3);
}

主.cpp

#include "city.h"
int main(){
    City myCity;
    myCity.addPerson();
}

看起来您实际上并没有在 Person 类中分配值,因此这就是您获取这些数据成员的随机值的原因。

它应该是:

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