[英]c++ compiling error for interface implementation with template
I am trying to implement interface with template for some class.我正在尝试为某些 class 实现与模板的接口。 I have code like this:我有这样的代码:
file.h文件.h
#pragma once;
class MySpecificClass {
std::string data;
unsigned int x;
unsigned int y;
unsigned int z;
public:
MySpecificClass(): data(""), x(0), y(0), z(0) {
}
MySpecificClass(std::string s, unsigned int xx, unsigned int yy, unsigned zz) : data(s), x(xx), y(yy), z(zz) {
}
};
template <class T>
class IFileClass {
public:
IFileClass(std::string f) : fileName(f) {
}
virtual void save(T c);
protected:
std::string fileName;
};
template <class T>
class FileWithClass : public IFileClass<T> {
public:
FileWithClass(std::string fn) : IFileClass<T>(fn) {
}
void save(T c) override {
std::cout << "FileWithClass save" << std::endl;
}
};
When I trying use it in main当我尝试在 main 中使用它时
main.cpp主文件
#include "file.h"
int main() {
// create object to save
MySpecificClass msc = {"My Test", 100, 200, 300};
FileWithClass<MySpecificClass> fsv = {"test.txt"};
fsv.save(msc);
}
I get a compile error like this:我收到这样的编译错误:
undefined reference to `IFileClass<MySpecificClass>::save(MySpecificClass)'
What is wrong?怎么了?
The template is not the problem here.模板不是这里的问题。 Virtual function without a definition is.没有定义的虚拟 function 是。
The C++ Standard specifies that all virtual methods of a class that are not pure-virtual must be defined. C++ 标准规定必须定义 class 的所有非纯虚拟方法。 In your base class you declare a virtual function save.在您的基础 class 中,您声明了一个虚拟 function 保存。 If it were not virtual then it would be OK to leave it without a definition (if it is not used - the linker wouldn't complain).如果它不是虚拟的,那么可以不定义它(如果不使用它 - linker 不会抱怨)。
But since it is virtual there are to options - give it an empty definition with {} or make it pure virtual with =0.但是因为它是虚拟的,所以有一些选项 - 用 {} 给它一个空定义,或者用 =0 使它成为纯虚拟。 Both variants are legal depending on what you want.这两种变体都是合法的,具体取决于您想要什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.