创建类对象时出错
Error creating a class object
我在创建一个简单的类对象时遇到问题。我创建了一个小程序来模拟这个问题。我有一个包含数据成员的类"人"string name
、string eye_color
和int 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;
}
相关文章:
- 在c++中访问int到类对象的映射时出错
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 按基类对象访问派生类资源时出错
- ./main:加载共享库时出错:libopencv_highgui.so.4.0:无法打开共享对象文件:没有这样的文件或
- 在 c++ 的构造函数中分配对象向量时出错
- 从主线程中询问运行对象表 (ROT) 时出错
- 加载共享库时出错:libbsoncxx.so._noabi:无法打开共享对象文件:没有此类文件或目录
- 从 Arduino 中的自定义C++库构造对象时出错
- 在 boost::heap::p riority_queue 中推送结构对象时出错
- 创建 OpenGL 对象期间出错
- 为什么在定义类之前声明类的对象会在友元类中给出错误,而在友元函数中不会出错
- 创建类对象时出错
- 尝试将对象用作类的属性时出错
- 擦除矢量中的对象时出错.如何将移动作业运算符添加到我的类中
- 编译创建 Eigen::ThreadPoolDevice 对象的代码时出错
- 尝试使用构造函数创建对象时出错
- 从模板类初始化对象时出错.参考类模板实例化
- 加载共享库时出错:无法在外部硬件上打开共享对象文件:
- 可变大小的对象可能无法初始化 尽管初始化了,但出错
- 删除时出错:表达式必须是指向完整对象类型的指针