选择要在编译时使用的派生类
Selecting which derived class to use at compile time
我认为这是一个非常简单的问题,但我对C++的了解不足以让它听起来很简单。
我有定义抽象基类ContinuousDistribution
和派生类(如Cauchy
或Normal
)的代码
我的目标是拥有变量A
的默认定义,但允许用户更改该定义,特别是更改变量的类型。(我不是说运行时重新定义,而是编译时重新定义)
所以在默认文件中,我会有
默认.cpp
...
Normal A(0., 20.); // Normal is the default
....
x = A.logpdf();
其在假定默认CCD_ 5分布的情况下编译和运行。
然后我希望用户创建一个"配置"文件,在该文件中可以更改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()
。
我该如何解决这个问题?
正如一条评论中所建议的那样,我还尝试使用类似default.cpp
中的Normal *A=new Normal(0,20);
,并在user2.cpp
中用A = new Cauchy(0,10);
重新分配它,但随后user2.cpp
由于A was not declared in this scope
而不编译。
如果您使用标头(这是一种很好的做法,所以您应该这样做),您可以执行以下操作:
默认.h
#ifndef _default_h_
extern Normal *A;
#define _default_h_
#endif
默认.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关键字告诉编译器在链接阶段的某个地方会有给定类型和名称的变量,并且使用基类指针可以将导数存储在自己中。
- 使用 std::enable_if 限制派生类的模板参数时出现编译错误
- 基于派生类型的编译时行为分支
- C++:编译对无关派生类、bug或特性的函数调用
- 如果所有派生类在编译时都是已知的,那么final关键字是否提供了优化
- 如何创建指向派生类的新指针,该派生类在C++编译时未知
- 从std::map派生的类不在Visual C++上编译(但在gcc和clang上编译)
- 在编译时间定义多个派生类
- 如果未实现虚函数,则大多数派生类无法编译,但如果一个基类未实现虚函数,则可以编译
- 为什么这两个涉及受保护派生类的C++示例的编译方式不同?
- 在向量中使用派生的可移动但不可压缩的会导致编译错误
- 选择要在编译时使用的派生类
- 通过迭代器调用功能无法在派生对象上编译
- OpenCV模板化代码在派生类中产生编译错误
- 在Linux上的命令行上编译QObject派生类
- 将模板方法移动到派生中断编译
- 重新编译二进制类或派生类,以便在基类中添加新方法
- 在派生类中缺少静态成员变量时强制编译错误
- 将派生对象声明为类中的私有成员时发生编译错误
- 无法使派生的 WebDuino 类工作 - 使用 'Web_HelloWorld.ino' 编译错误
- 从嵌套在模板中的类派生时编译问题