创建类的空实例

Creating an empty instance of a class

本文关键字:实例 创建      更新时间:2023-10-16

好的,我有一个类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;
}

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