【问题标题】:Creating an empty instance of a class创建一个类的空实例
【发布时间】:2013-10-20 23:31:22
【问题描述】:

好的,我有一个班级Set,他将vector<int> 作为其数据负载。它有一个接受string 作为参数的构造函数,例如Set test = Set("1 2 3 4 5 6"); 我有一个函数可以读取该行,并将其解析为vector<int>,我可以对Set 执行操作。当调用Set test = Set(""); 时出现问题,我的构造函数无法生成Set,因为它没有什么可解析的。我的程序哪儿也去不了。我尝试在构造函数中放置 if else 语句,但如何声明一个空的 set

现在我遇到了分段错误。

#include "Set.h"

using namespace std;

/***************************************************************************************
 * Constructors and Destructors
**/
Set::Set(){
}
Set::Set(string inputString) {
    if(inputString != ""){
        readLine(inputString);
    }
    else{
        //I've tried several things here, none of which work.
    }
}


Set::~Set(){
}

/***************************************************************************************
 * readLine function
 * 
 * This function takes in a string, takes the next int, and stores in in a vector.
 *
 * Parameters: string, the string to be parsed.
 * 
**/
void Set::readLine(string inString){
        ScanLine scanLine;
        scanLine.openString(inString);
        while(scanLine.hasMoreData()){
            addToSet(scanLine.nextInt());
        }
}

/***************************************************************************************
 * addToSet function
 * 
 * This function takes in a int that is an element and adds it to "this" Set.
 *
 * Parameters: int, the element to be added.
 * Return: int, the value that was added.
 * 
**/
int Set::addToSet(int element){
    int returnValue = -1;
    if(!containsElement(element)){
        this->theSet.push_back(element);
        returnValue = element;
    }
    return returnValue;
}

【问题讨论】:

  • 您发布的代码有什么问题?是什么让您相信您需要用任何东西替换 //I've tried several things here, none of which work.
  • 如果我省略 else 语句,我会得到分段错误 11。这让我觉得我需要一个 else。
  • 您发布的代码不对分段错误负责。提供short, self-contained, correct example
  • 分段错误 11 的最可能原因是什么?
  • 访问不属于您的应用程序的内存。这种情况最常发生在取消引用未初始化的指针或读取或写入超出数组边界时。

标签: c++ class parameters constructor string


【解决方案1】:

我找到了解决方案。在我的 equals 函数中,我有 if(!set1.size() == set2.size()),而我应该有 if(set1.size() != set2.size()),但由于某种原因导致了分段错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-01
    • 1970-01-01
    • 2012-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-20
    • 1970-01-01
    相关资源
    最近更新 更多