我的.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;
我得到:在抛出'std :: logic_error'的实例后终止调用 what():basic_string :: _ S_construct null无效
是构造函数问题还是语法错误?
答案 0 :(得分:3)
问题出在默认构造函数的初始化列表中:
name(0)
尝试使用带有空指针值的C样式字符串指针char const*
的构造函数初始化字符串。然后,您将收到运行时错误,因为您不允许将空指针传递给该构造函数。
要将字符串初始化为空,请指定默认初始化(或者,迂腐地,值初始化,这对于此类型来说相同)
name()
或将其从初始化列表中删除。
答案 1 :(得分:0)
假设上面的代码中没有故意的拼写错误,在非常关键的位置会丢失分号,以及在标题中看起来不正确且缺少声明的大括号使用。
新的行和/或字符会以// 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;