gpt4 book ai didi

c++ - "Warning: Can' t 使用 GCC 和 GDB(代码块)为值 XXX 值找到虚拟表的链接器符号

转载 作者:可可西里 更新时间:2023-11-01 18:26:47 26 4
gpt4 key购买 nike

我收到一个运行时错误(“无法写入内存”),在通过调试器检查后,该错误导致标题中出现警告。

标题如下:

组件.h:

#ifndef COMPONENTE_H
#define COMPONENTE_H

using namespace std;

class componente
{
int num_piezas;
int codigo;
char* proovedor;
public:
componente();
componente(int a, int b, const char* c);
virtual ~componente();
virtual void print();

};

#endif // COMPONENTE_H

complement.h 实现

#include "Componente.h"
#include <string.h>
#include <iostream>

componente::componente()
{
num_piezas = 0;
codigo = 0;
strcpy(proovedor, "");
//ctor
}

componente::componente(int a = 0, int b = 0, const char* c = "")
{
num_piezas = a;
codigo = b;
strcpy(proovedor, "");
}

componente::~componente()
{
delete proovedor;//dtor
}

void componente::print()
{
cout << "Proovedor: " << proovedor << endl;
cout << "Piezas: " << num_piezas << endl;
cout << "Codigo: " << codigo << endl;
}

teclado.h

#ifndef TECLADO_H
#define TECLADO_H

#include "Componente.h"


class teclado : public componente
{
int teclas;
public:
teclado();
teclado(int a, int b, int c, char* d);
virtual ~teclado();
void print();


};

#endif // TECLADO_H

teclado.h 实现

#include "teclado.h"
#include <iostream>

teclado::teclado() : componente()
{
teclas = 0;//ctor
}

teclado::~teclado()
{
teclas = 0;//dtor
}

teclado::teclado(int a = 0, int b = 0, int c = 0, char* d = "") : componente(a,b,d)
{
teclas = c;
}

void teclado::print()
{
cout << "Teclas: " << teclas << endl;
}

我得到运行时错误的主要方法如下:

#include <iostream>
#include "teclado.h"

using namespace std;

int main()
{
componente a; // here I have the breakpoint where I check this warning
a.print();
return 0;
}

但是,如果我没有创建“componente”对象,而是创建了“teclado”对象,我不会收到运行时错误。我在调试期间仍然收到警告,但程序按预期运行:

#include <iostream>
#include "teclado.h"

using namespace std;

int main()
{
teclado a;
a.print();
return 0;
}

这将返回“Teclas = 0”加上“按任意键...”。

你知道链接器为什么会遇到这个问题吗?它不会在我调用虚函数时出现,而是在构建之前出现。

最佳答案

我可以看到两个错误:

strcpy(proovedor, "");  // No memory has been allocated to `proovedor` and
// it is uninitialised.

因为它是未初始化的,所以这可能会覆盖进程内存中的任何地方,因此可能会破坏虚拟表。

您可以将其更改为(在两个构造函数中):

proovedor = strdup("");

析构函数在 proovedor 上使用了不正确的 delete:

delete proovedor; // should be delete[] proovedor

由于这是 C++,您应该考虑使用 std::string 而不是 char*

如果您不更改为 std::string,那么您需要:

  1. >如果您有一个动态分配的成员变量,则实现复制构造函数和赋值运算符,因为默认版本不正确,或者
  2. >将复制构造函数和赋值运算符设为私有(private),使其无法使用。

关于c++ - "Warning: Can' t 使用 GCC 和 GDB(代码块)为值 XXX 值找到虚拟表的链接器符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8695411/

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