C重写C++方法

C overriding C++ method

本文关键字:方法 C++ 重写      更新时间:2023-10-16

expr.hpp

typedef int (*evaluate)(PExp);
typedef void (*printTo)(PExp, FILE *);
typedef void (*Exp_free)(PExp);
class Expression {
public:
virtual int  evaluate()          abstract; 
virtual void printTo(FILE * out) abstract;  
virtual void free();                       
};
class Value : public Expression {
protected:
int value;
Value(int value);
public:
int evaluate();
};

表达式.h

#include <stdlib.h>
#include <stdio.h>
typedef struct expression Expression;
typedef Expression * PExp;
typedef int (*evaluate)(PExp);
typedef void (*printTo)(PExp, FILE *);
typedef void (*Exp_free)(PExp);
typedef struct {
evaluate exp_evaluate;
printTo exp_printTo;
Exp_free exp_free;
} vTable;
struct expression {
vTable * v;
};
void expression_init(PExp this);
void exp_free(PExp this);

值.h

#include "Expression.h"
typedef struct {
Expression super;
int value;
} Value;
void value_init(Value * this, int value);
int value_evaluate(Value * this);

常数.h

typedef struct {
Value super;
} Constant;
void constant_init(Constant * this, int value);
void constant_free(Constant * this);
void constant_printTo(Constant * this, FILE * out);

expr.h

#include "Expression.h"
#include "Value.h"
#include "Constant.h"

main.c

#include "expr.h"
void constant_init(Constant * this, int value) {
_ZN5ValueC2Ei((Value *)this, value);
printf("%dn", this->super.super.v->exp_evaluate((PExp)this));
this->super.super.v->exp_printTo = (printTo)constant_printTo; // MARK
}
void constant_printTo(Constant * this, FILE * out) {
fprintf(out, "%d", this->super.value );
putchar('n');
}

我目前正在尝试实现一些代码,这些代码在使用C++的同时在C中构造一些对象。类"Expression"answers"Value"是在C++中给定的,我必须实现类"Constant",它扩展了C中的"Value"。我不能更改C++文件(包括新文件)中的任何内容,所以这就是为什么我用"Value"构造函数的错误名称来调用它的原因。问题是:我可以调用类"Value"中定义的方法exp_evaluate,但当我试图覆盖方法exp_printTo(有标记的行)时,它总是给我Segmentation Fault,那么我在这里做错了什么?。如果我尝试调用该方法,而不是尝试为函数指针分配另一个值,它会按预期终止,因为它是一个纯虚拟方法。以下是makefile,显示"main"是用3个C++文件和main.C:编译的

main: use-expr.o expr.o main.o
g++ -o use-expr-c use-expr.o expr.o main.o -g
use-expr.o: use-expr.cpp expr.hpp
g++ -Wall -pedantic -g -c use-expr.cpp -g
expr.o: expr.cpp expr.hpp
g++ -Wall -pedantic -g -c expr.cpp -g
main.o: main.c
gcc -Wall -pedantic -std=c99 -g -c -o main.o main.c -g

它都是编译的,我得到的唯一错误是在运行时。我希望有足够的信息。提前谢谢。

我建议您实现一个调用C++的小包装器(在C++中),并使用extern C使那里的函数具有C链接。这是一个比调用损坏的C++名称更可靠的方法。

如果你真的想知道发生了什么,恐怕是时候爆发gdb了。