gpt4 book ai didi

c++ - 在使用 C++ 默认构造函数时遇到问题?

转载 作者:行者123 更新时间:2023-11-30 02:48:26 26 4
gpt4 key购买 nike

我的 .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 无效

这是构造函数问题还是语法错误?

最佳答案

问题出在默认构造函数的初始化列表中:

name(0)

这尝试使用采用 C 风格字符串指针的构造函数初始化字符串,char const*,具有空指针值。然后您会收到运行时错误,因为您不允许将空指针传递给该构造函数。

要将字符串初始化为空,请指定默认初始化(或者迂腐地指定值初始化,这对于这种类型来说是一样的)

name()

或将其保留在初始化列表之外。

关于c++ - 在使用 C++ 默认构造函数时遇到问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22002508/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com