1
我在創建簡單類對象時遇到問題。我創建了一個小程序來模擬問題。我有一個班級「Person」,其數據成員爲string name
,string eye_color
和int pets
。當我打電話Person new_person("Bob", "Blue", 3)
,我的調試器顯示此爲new_person
的價值:創建類對象時出錯
{name=""eye_color=""pets=-858993460}
我看以前的項目,我不得不用這個沒有問題,我沒有察覺什麼...我是什麼失蹤?
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();
}
糟糕!不知道我是如何在經過多次審查之後忽視這一點的。我想我正在初始化值,但不分配給任何東西。謝謝! – velkoon
我不知道確切的原因是什麼,但是在很多編程語言中,您只需在一行中編寫一個變量,並且該變量有效且不影響任何AFAIK。 – OJ7