构造函数中的分段错误 这是用 >每一个类I尝试在C++中生成的。从java迁移时,我发现问题主要在于生成类。我运行valgrind,它在构造函数中,看起来是 ==30214== Memcheck, a memory error detector ==30214== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al. ==30214== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info ==30214== Command: ./CoC ==30214== ==30214== ==30214== Process terminating with default action of signal 11 (SIGSEGV) ==30214== Bad permissions for mapped region at address 0x404B4F ==30214== at 0x4C2B9EC: strcat (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) ==30214== by 0x404220: Model::Model(std::string) (in /home/kronus/Apollo/CoC) ==30214== by 0x402617: main (in /home/kronus/Apollo/CoC)

构造函数中的分段错误 这是用 >每一个类I尝试在C++中生成的。从java迁移时,我发现问题主要在于生成类。我运行valgrind,它在构造函数中,看起来是 ==30214== Memcheck, a memory error detector ==30214== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al. ==30214== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info ==30214== Command: ./CoC ==30214== ==30214== ==30214== Process terminating with default action of signal 11 (SIGSEGV) ==30214== Bad permissions for mapped region at address 0x404B4F ==30214== at 0x4C2B9EC: strcat (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) ==30214== by 0x404220: Model::Model(std::string) (in /home/kronus/Apollo/CoC) ==30214== by 0x402617: main (in /home/kronus/Apollo/CoC),c++,header-files,memory-segmentation,C++,Header Files,Memory Segmentation,如您所见,我试图将这个模型类的构造函数调用到main方法中。下面是构造函数的代码 Model::Model(std::string filename) { m_TotalFaces = 0; m_model = lib3ds_file_load(filename.c_str()); // If loading the model failed, we throw an exception if(!m_model) { throw strcat("Un

如您所见,我试图将这个模型类的构造函数调用到main方法中。下面是构造函数的代码

Model::Model(std::string filename)
{
m_TotalFaces = 0;
m_model = lib3ds_file_load(filename.c_str());
    // If loading the model failed, we throw an exception
    if(!m_model)
    {
           throw strcat("Unable to load ", filename.c_str());
    }
}

当它被调用时,它以分段错误结束。重要提示:我已经在头文件中声明了类。这就是我得到错误的时候。我将该类放在源文件中,它运行良好。我做错了什么?

您正在向一个错误的常量字符串追加内容:

strcat("Unable to load ", filename.c_str());
         ^ you can't append to constant
阅读以下内容:
您可能希望避免使用字符串作为异常类,因为它们本身可以在使用过程中引发异常


第二个:

strcat
尝试将第二个参数指向的字符串写入第一个参数指向的字符串末尾。由于第一个参数是字符串文字(应视为只读),因此会出现一个错误


我建议学习C++,就像它是完全不同于java的语言一样,因为否则你会认为类似的函数也会起作用。那很危险。猴子可以通过在键盘上捣碎自己的脸来学习Java。C++有不确定的行为,它可能在你的机器上正确地运行,但是在另一个核上发射核导弹。

理想地抛出一个真正的<代码>:ST::例外< /代码>或者它的一个派生。几乎第三的答案与你,你解释得很好。你是令人惊异的哈哈。非常感谢。我会尽量不让我的愚蠢问题充斥这个网站,但我学到了一些新东西!哈哈。你能告诉我为什么从源代码调用时它会工作吗?因为这是从头文件调用的。因为它一直发生在我身上…未定义的行为。。。有时,未定义的行为似乎起作用,而有时则不起作用。这就是为什么它如此危险的部分原因。你在读哪本书?这本。只是。。每次我试着上一节课,它都是这样做的。现在它看起来像是任何一种内存被改变的类。所以我不能在C++中这样做?你不能,也不应该,至少在C++中。Strut在C代码中是可以接受的,但是在C++代码中有不同的方法来做(例如,参见Selvia.JooEux对你的问题的注释)。“尝试检索URL时遇到以下错误:…”。请告诉我这本书的书名和作者。抛出的C++无需使用C字符串操作方法是throw std::runtime_error(“无法加载”+文件名)