【问题标题】:Selecting which derived class to use at compile time在编译时选择要使用的派生类
【发布时间】:2023-04-04 19:39:01
【问题描述】:

我认为这是一个非常简单的问题,但我对 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
....

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

我该如何解决这个问题?

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

【问题讨论】:

  • 我不明白你在做什么......你为什么要重新声明一个变量......在c ++中你只能声明具有相同名称的变量,只要它们在不同的范围
  • 看起来你正试图弄乱全局变量。尝试在没有它们的情况下编写代码。
  • 您是否尝试过使用指向基类的指针并重新分配它?像这样:正常 *A=new Normal(0,20); ... A = 新法线(0,10); .... A = 新柯西(0,10);
  • @Victor 这似乎是一个不错的选择,但我在重新分配时得到了一个multiple definition of 'A'
  • 能否请您提供更完整的源文件示例,最好包含包含。您是否将 cpp 文件相互包含在内?

标签: c++ class type-conversion


【解决方案1】:

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

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 关键字告诉编译器在链接阶段的某个地方会有给定类型和名称的变量,并且使用基类指针允许在其自身中存储派生类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-05
    • 1970-01-01
    • 1970-01-01
    • 2020-12-12
    相关资源
    最近更新 更多