创建一个类的空实例

时间:2013-10-20 23:31:23

标签: c++ class parameters constructor string

好的,我有一个班级Set,他将vector<int>作为其数据有效负载。它有一个构造函数接受string作为参数,例如Set test = Set("1 2 3 4 5 6");我有一个读取该行的函数,并从那里将它解析为vector<int>我可以对Set执行操作{1}}。调用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;
}

1 个答案:

答案 0 :(得分:0)

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

相关问题