Hea*_*iff 7 c++ gcc gdb virtual-functions
我得到一个运行时错误("无法写入内存"),在通过调试器检查后,会导致警告.
标题如下:
componente.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
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
我得到运行时错误的主要方法如下:
#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;
}
Run Code Online (Sandbox Code Playgroud)
但是,如果不是创建"组件"对象,而是创建"teclado"对象,我不会收到运行时错误.我仍然在调试期间收到警告,但程序按预期运行:
#include <iostream>
#include "teclado.h"
using namespace std;
int main()
{
teclado a;
a.print();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这将返回"Teclas = 0"加上"按任意键......"的事情.
你知道连接器为什么会遇到麻烦吗?当我调用虚拟功能时,但在构建之前,它不显示.
hmj*_*mjd 10
我可以看到两个错误:
strcpy(proovedor, ""); // No memory has been allocated to `proovedor` and
// it is uninitialised.
Run Code Online (Sandbox Code Playgroud)
由于它未初始化,这可能会覆盖进程内存中的任何位置,因此可能会破坏虚拟表.
您可以将其更改为(在两个构造函数中):
proovedor = strdup("");
Run Code Online (Sandbox Code Playgroud)
析构函数使用不正确delete的proovedor:
delete proovedor; // should be delete[] proovedor
Run Code Online (Sandbox Code Playgroud)
因为这是C++,你应该考虑使用std::string而不是char*.
如果你没有改变std::string那么你需要: