【问题标题】:cout resulting terminate called after throwing an instance of 'std::length_error'cout 在抛出 'std::length_error' 的实例后调用终止
【发布时间】:2015-05-19 12:11:00
【问题描述】:

当我运行我的程序时它崩溃并出现以下错误:

在抛出 'std::length_error' 的实例后调用终止 什么():basic_string::_S_create 中止(核心转储)

我通过以下代码得到:

#include <iostream>
#include <string>
using namespace std;

class Cargo
{
    string nm;
public:
    Cargo(const string& name): nm(name)
    {

    }
    Cargo& operator=(const Cargo& )
    {
        cout<<"inside Cargo::operator=()"<<endl;
        return *this;
    }

    friend ostream& operator<<(ostream& os, const Cargo& ca)
    {
        return os<<"Cargo name: "<<ca.nm;
    }
};

class Truck
{
    Cargo b;
    string name;
public:
    Truck(const string& nm):b("Cargo" + name)
    {
        name = nm;
    }

    void print()
    {
        cout << "name: " << name << endl;
        cout << b << endl;
    }
};

int main()
{
    Truck a("Truck a"), b("Truck b");
    a = b;
    a.print();
    b.print();
}///~:

【问题讨论】:

  • 此时Truck的构造函数中的b("Cargo" + name)name未初始化。
  • @RichardCritten,谢谢,我明白了

标签: c++


【解决方案1】:

在您的 Truck 构造函数中:

Truck(const string& nm):b("Cargo" + name)
{
    name = nm;
}

您将Truck 类的name 属性作为参数发送给b,该属性未初始化。我猜你想传递你的 nm 参数:

Truck(const string& nm):b("Cargo" + nm)
{
    name = nm;
}

【讨论】:

    【解决方案2】:

    在卡车上你有b("Cargo" + name)name 还没有值,因为你还没有进入构造函数。如果将其更改为b("Cargo" + nm),它将修复运行时错误。见this 实例

    您还应该将初始化器列表中的name 初始化为:

    Truck(const string& nm):b("Cargo" + nm), name(nm) {}
    

    可以有一个空的构造函数,我更喜欢这样做,因为它表明构造函数所做的只是初始化成员变量,没有别的。

    【讨论】:

    • 再解释一下错误信息:成员变量是按照声明的顺序构造的;所以 "Cargo" + name 实际上是在 name 调用其构造函数之前处理的,导致未定义的行为。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-08
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多