选择在编译时使用哪个派生类

时间:2017-11-07 16:30:20

标签: c++ class type-conversion

我认为这是一个非常简单的问题,但我不太了解C ++,听起来很简单。

我有定义抽象基类ContinuousDistribution的代码,以及CauchyNormal等派生类。 我的目标是拥有变量A的默认定义,但允许用户更改该定义,特别是更改变量的类型。 (我不是指运行时重新定义,它是编译时重新定义)

所以在默认文件中我会有

default.cpp

... 
Normal A(0., 20.);  // Normal is the default
....
x = A.logpdf();

编译并运行,假设默认Normal分布。

然后我希望用户创建一个“配置”文件,其中可以更改A的定义。在另一个文件中,将与 default.cpp一起编译,我们可以

user1.cpp

... 
Normal A(0., 10.);  // change the arguments of Normal
....
call some functions defined in default.cpp, which use methods of A
....

或另一个

user2.cpp

... 
Cauchy A(0., 10.);  // change the type of A
....
call some functions defined in default.cpp, which use methods of A
....

要解决此问题,我尝试在extern Normal A中使用default.cpp,但这不允许将变量重新定义为Cauchy。 我还尝试使用extern ContinuousDistribution A中的default.cpp,但这也无效。 如果A的定义已从default.cpp中移除,则我无法使用error: ‘A’ was not declared in this scope进行编译,因为我使用了A.logpdf()

我该如何解决这个问题?

正如评论中所建议的那样,我也尝试使用指针 Normal *A=new Normal(0,20);中的default.cpp并在A = new Cauchy(0,10);中将其与user2.cpp重新分配,但user2.cpp无法编译,因为A was not declared in this scope

1 个答案:

答案 0 :(得分:0)

如果你使用标题(这是一个很好的做法,所以你应该这样做),你可以按如下方式进行:

<强> default.h

#ifndef _default_h_
    extern Normal *A;
#define _default_h_
#endif

<强> default.cpp

#include "default.h"

... 
Normal *A = new Normal(0., 20.);  // Normal is the default
....
x = A->logpdf();
...

<强> user1.cpp

 #include "default.h"

 ...
 delete A; // Free up memory
 A = new Normal(0., 10.);  // change the arguments of Normal
 ...
 call some functions defined in default.cpp, which use methods of A
 ....

<强> user2.cpp

 #include "default.h"

 ...
 delete A; // Free up memory
 A = new Cauchy(0., 10.);  // change the arguments of Normal
 ...
 call some functions defined in default.cpp, which use methods of A
 ....

Extern关键字告诉编译器在链接阶段会有某个给定类型和名称的变量,并且使用基类指针允许存储衍生物本身。

相关问题