繁体   English   中英

创建类对象时出错

[英]Error creating a class object

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

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

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

#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(){}

城市

#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();
}

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

它应该是:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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