我正在使用向量v
来存储名为t_display
的类对象。我已经检查过调试器,我可以看到显示对象是否正确实例化。但是,当我将其传递到包含v.push_back()
或v.insert()
的向量时,它会将每个值存储为-842150451
。我可以在print语句和调试器中看到这一点,我无法弄清楚它为什么以这种方式存储对象。此外,它每次执行程序时都以这种方式存储整数值,这使我相信它不是内存问题,虽然我无法确定。我已经检查了堆栈溢出和cppreference。任何意见,将不胜感激。
这是我创建对象并传递给向量的类。我只想让向量在第一个元素中包含新制作的对象t_display。
#include <crtdbg.h>
#include <iostream>
#include <string>
#include <vector>
#include <forward_list>
using namespace std;
#include "Display.h"
#include "Animation.h"
void Animation::InsertFrame() {
int numDisplays;
vector <Display>v;
int p_x;
int p_y=0;
int p_duration=0;
string p_name;
string frameName;
cout << "Insert a Frame in the Animation\nPlease enter the Frame filename" << endl;
cin >> frameName;
cout << "Entering the Frame Displays (the sets of dimensions and durations) " << endl;
cout << "Please enter the number of Displays :" << endl;
cin >> numDisplays;
vector <Display>::iterator it;
it = v.begin();
while (numDisplays > 0) {
cout << "Please enter pixel x for Display #0 pixel_x:";
cin >> p_x;
cout << "\nPlease enter pixel y for Display #0 pixel_y:" << endl;
cin >> p_y;
cout << "\nPlease enter the duration sec for this Display :" << endl;
cin >> p_duration;
cout << "\nPlease enter the name for this Display : " << endl;
cin >> p_name;
Display t_display = Display(p_x, p_y, p_duration, (char *)p_name.c_str());
//it = v.insert(it, t_display);
v.push_back(t_display);
numDisplays--;
}
// Display.h
#pragma once
class Display
{
int pixel_x;
int pixel_y;
int duration;
char* name;
public:
Display(int x, int y, int duration, char* name);
Display(const Display&);
~Display();
friend ostream& operator<<(ostream&, Display&);
};
## Display.cpp ##
#include <crtdbg.h>
#include <iostream>
#include <string>
#include <vector>
#include <forward_list>
using namespace std;
#include "Display.h"
int q = 0;
Display::Display(int x, int y, int d, char* n):pixel_x(x), pixel_y(y), duration(d), name(n) {}
Display::Display(const Display&) {
}
Display::~Display() {
}
答案 0 :(得分:0)
事实证明我没有写复制构造函数。