【发布时间】: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