簡體   English   中英

c++ 使用模板實現接口的編譯錯誤

[英]c++ compiling error for interface implementation with template

我正在嘗試為某些 class 實現與模板的接口。 我有這樣的代碼:

文件.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;
    }
};

當我嘗試在 main 中使用它時

主文件

#include "file.h"
int main() {
    // create object to save
    MySpecificClass msc = {"My Test", 100, 200, 300};
    FileWithClass<MySpecificClass> fsv = {"test.txt"};
    fsv.save(msc);
}

我收到這樣的編譯錯誤:

undefined reference to `IFileClass<MySpecificClass>::save(MySpecificClass)'

怎么了?

模板不是這里的問題。 沒有定義的虛擬 function 是。

C++ 標准規定必須定義 class 的所有非純虛擬方法。 在您的基礎 class 中,您聲明了一個虛擬 function 保存。 如果它不是虛擬的,那么可以不定義它(如果不使用它 - linker 不會抱怨)。

但是因為它是虛擬的,所以有一些選項 - 用 {} 給它一個空定義,或者用 =0 使它成為純虛擬。 這兩種變體都是合法的,具體取決於您想要什么。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM