我已经在我的.h和.cpp文件中有一个构造函数,它接受一些参数,但我还需要一个默认参数,我不确定如何设置它,因为我尝试它的方式可以编译,但当我运行我的测试文件时得到错误。这是我的.h文件
public:
Class();
Class(const std::string &, const int)
void getInfo();
std::string listItem();
private:
std::string name;
int quantity;这是我的.cpp文件
Class::Class()
: name(0), quantity(0)
{
Class::Class(const string &nam, const int quant)
: name(nam),quantity(quant)
{
}
void Class::getInfo()
{
cout << "Enter Name: ";
cin >> name
cout << "Enter quantity: ";
cin >> quantity;
}
string Class::listItem()
{
ostringstream outputString;
outputString << getName() << getQuantity();
return outputString.str();
}这是我的测试中引起麻烦的部分:
const int shortList = 2;
array<Class*, shortList> newList;
for (int i=0; i< 2; i++){
Class *p = new Class();
p->getInfo();
newList[i] = p;
}
cout << "newList contains: " << endl;
for (Class* p : newList)
cout << p->listItem() << endl;I get : terminate在抛出'std::logic_error‘的实例后调用what():basic_string::_S_construct null无效
是构造函数的问题还是语法错误?
发布于 2014-02-25 09:06:56
问题出在默认构造函数的初始值列表中:
name(0)这会尝试使用构造函数初始化字符串,该构造函数采用C样式的字符串指针char const*,指针值为空。然后你会得到一个运行时错误,因为你不允许向该构造函数传递空指针。
要将字符串初始化为空,可以指定默认初始化(或者手动指定值初始化,这等同于此类型的值初始化)
name()或者将其从初始化器列表中删除。
发布于 2014-02-25 10:20:45
假设上面的代码中没有故意的打字错误,在非常关键的位置缺少分号,大括号的使用看起来不正确,标题中缺少声明。
新行和/或字符使用以// added ...开头的注释进行注释
从头文件开始:
class Class // added
{ // added
public:
Class();
Class(const std::string &, const int); // added semi-colon
void getInfo();
std::string listItem();
private:
std::string name;
int quantity;
}; // added closing curly brace and semi-colon.cpp源文件:
Class::Class()
: name(""), quantity(0) // modified name initial value to the empty string
{
} // added curly brace
Class::Class(const string &nam, const int quant)
: name(nam),quantity(quant)
{
}
void Class::getInfo()
{
cout << "Enter Name: ";
cin >> name; // added semi-colon
cout << "Enter quantity: ";
cin >> quantity;
}
string Class::listItem()
{
ostringstream outputString;
outputString << getName() << getQuantity();
return outputString.str();
}稍后,引起问题的代码是:
const int shortList = 2;
array<Class*, shortList> newList;
for (int i=0; i< shortList; i++){ // changed bounds check for i to the const int shortList
Class *p = new Class();
p->getInfo();
newList[i] = p;
}
cout << "newList contains: " << endl;
//
// changed to declare auto instead.
// As a pointer declaration, there is a chance the Class copy constructor is being called
// inside the loop body prior to the dereference. It should not be, but...
// In my opinion, it is much more likely that setting the name to a zero initial value
// in the Class() constructor is the real problem cause as Mike says above.
//
for (auto p : newList)
cout << p->listItem() << endl;https://stackoverflow.com/questions/22002508
复制相似问题