【发布时间】:2021-12-20 19:00:36
【问题描述】:
下面是我的代码。我删除了与问题无关的内容以保持简洁:
IChip.hpp(根抽象类)
class IChip {
public:
virtual bool test() noexcept = 0;
};
IMemory.hpp(包含所有内存通用的一些功能的摘要,读/写用于说明)
#include "IChip.hpp"
template <typename TAddr, typename TWord>
class IMemory: public IChip {
protected:
...
public:
virtual TWord read(const TAddr addr) const noexcept = 0;
virtual void write(const TAddr addr, const TWord data) const noexcept = 0;
...
bool test() noexcept final override;
};
IMemory.cpp
#include "IMemory.hpp"
template <typename TAddr, typename TWord>
bool IMemory<TAddr, TWord>::test() noexcept {
std::cout << "IMemory:test()" << std::endl;
...
return true;
}
// Explicit instantiation. (Actually resides in a separate file IMemory.impl.cpp, but included here for clarity)
template class IMemory<uint16_t, uint8_t>;
HM62256.hpp(为了说明再次读/写)
#include "IMemory.hpp"
class HM62256: public IMemory<uint16_t, uint8_t> {
private:
...
public:
...
uint8_t read(uint16_t addr) const noexcept final override;
void write(uint16_t addr, uint8_t data) const noexcept final override;
...
};
HM62256.cpp
#include "HM62256.hpp"
uint8_t HM62256::read(uint16_t addr) const noexcept {
uint8_t result = 0;
...
return result;
}
void HM62256::write(uint16_t addr, uint8_t data) const noexcept {
...
}
main.cpp
int main(int argc, char *argv[]) {
const uint8_t ADDR_PINS[] = {4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18};
const uint8_t DATA_PINS[] = {19, 20, 21, 22, 23, 24, 25, 26};
HM62256 *device = new HM62256(ADDR_PINS, DATA_PINS, 2, 3, 27);
device->test(); // (1)
delete device;
}
我的主要问题如下:
- 此代码编译时没有问题(甚至没有警告)。
- 我的期望是 (1) 处的
device->test()将执行 HM62256 从 IMemory 继承的test()方法。因此它应该将 IMemory:test() 打印到控制台。它不是。我在上述test()方法上设置了断点,但调试器没有命中它们。相反,执行只是简单地进行,没有任何内容打印到控制台。我在delete device;上设置了一个断点,它确实命中了它。
我的第二个问题是,由于代码编译得很好,(1) 处的函数调用必须调用一些东西,对吗? 什么它叫什么?
附加信息:
- 编译器:针对 arm-linux 和 C++20 的 GCCC 8.3.0
- 使用 CMake
【问题讨论】:
-
这能回答你的问题吗? Why can templates only be implemented in the header file?
IMemory.cpp中的代码需要在头文件中。 -
@RichardCritten 在 IMemory.cpp 中有一个明确的实例化,所以至少从这个角度来看,代码是好的。
-
使用调试器进入对
test的调用,看看你的结果。 -
@S.Saad 由于 Godbolt 无法执行 ARM 代码,请参阅“执行代码”程序集上方的“输出”选项卡选项。那里的代码是正确的,它也必须在 ARM 上工作。你的问题在别的地方。也许尝试从头开始重新编译所有内容?
标签: c++ templates inheritance