[英]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
. 我有一个“ Person”类,其中的数据成员为string name
, string eye_color
和int pets
。 When I call Person new_person("Bob", "Blue", 3)
, my debugger shows this as the new_person
's value: 当我调用Person new_person("Bob", "Blue", 3)
,调试器将其显示为new_person
的值:
{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 人.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 city.cpp
#include "city.h"
City::City(){}
City::~City(){}
void City::addPerson(){
Person new_person("Bob", "Blue", 3);
}
main.cpp 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. 看起来您实际上并没有在Person类中分配值,所以这就是为什么您要为这些数据成员获取随机值的原因。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.