簡體   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