在类构造函数中使用vector时发生运行时错误?

时间:2020-08-06 07:10:15

标签: c++ vector runtime-error

嗨,我无法在构造函数中使用向量。我正在尝试将包含[x,y]坐标的向量解析为对象。

我得到的错误是运行时错误和错误的分配。

有什么我想念的吗?

我必须使用动态内存分配吗?

ShapeTwoD(子类正方形的父类):

class ShapeTwoD {

protected:
  string name;
  bool containsWarpSpace;
  vector<string> vect;

private:
public:
  ShapeTwoD() {}

  ShapeTwoD(string name, bool containsWarpSpace, vector<string> vect) {
    this->vect = vect;
    this->name = name;
    this->containsWarpSpace = containsWarpSpace;
  }

是ShapeTwoD子级的Class Square:

class Square : public ShapeTwoD {

public:
  Square() : ShapeTwoD(name, containsWarpSpace, vect) {
    this->vect = vect;
    this->name = name;
    this->containsWarpSpace = containsWarpSpace;
  }

  ~Square() {}
};

主要功能:

  vector<string> temp;

  string merge;

  for (int i = 0; i < 4; i++) {
    cout << "Please enter x-ordinate of pt " << i + 1 << " :";
    cin >> x;
    cout << "Please enter y-ordinate of pt " << i + 1 << " :";
    cin >> y;

    merge = x + ", " + y;

    temp.push_back(merge);
  }
  Square obj;

  obj.setName(shape);
  obj.setCoord(temp);

  if (specialtype == "ws") {
    obj.setContainsWarpSpace(true);
  }

  else if (specialtype == "ns") {
    obj.setContainsWarpSpace(false);
  }

  myvector.push_back(obj);
  temp.clear();

  cout << "\nRecords successfully stored. Going back to main menu ...\n"
       << endl;
}

enter image description here

2 个答案:

答案 0 :(得分:1)

在您的Square构造函数中,您没有传递任何参数:

Square() : ShapeTwoD(name,containsWarpSpace,vect){
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^

这意味着名称 containsWarpSpace vect 指的是尚未初始化的父类字段(因为ShapeTwoD构造函数的工作)。因此,您要获取未初始化的变量,并将它们传递给构造函数以初始化这些相同的变量。更明确地说,您正在做什么

Square():ShapeTwoD(this->ShapeTwoD::name, 
    this->ShapeTwoD::containsWarpSpace, this->ShapeTwoD::vect){

您应该将它们传递给:

Square(string name, bool containsWarpSpace, vector<string> vect)
    :ShapeTwoD(name,containsWarpSpace,vect) {

或通过明智的默认设置:

Square() : ShapeTwoD("", false, {}) {

答案 1 :(得分:0)

问题是:

@JsonIgnoreProperties(ignoreUnknown = true) public class WarningsClass { private String Message; public String getMessage() { return Message; } public void setMessage(String message) { Message = message; } }

merge = x + ", " + y;", "(以null结尾的字符数组)。作为数组,它衰减到指针(const char[3]),由于与const char *相加,其指针偏移了x+y。结果指针指向一个未知的内存位置。不保证下一个空字节驻留在可访问的地址范围内;即使该字节位于可访问的地址中,输出也不会有意义;因为您正在触发UB。 您可以这样修复它:

int

关于, FM。