![](/img/trans.png)
[英]Function defined in the header and called from the cpp file error
[英]undefined reference error while calling a function from user defined header file and it's implementation is in .cpp file
我所做的是一個fstreamExtension
類,該類公開繼承了fstream
class
。
fstreamExtension.h:
#include <fstream>
#include <string>
#include <vector>
#ifndef FSTREAMEXTENSION_H
#define FSTREAMEXTENSION_H
class fstreamExtension : public std::fstream
{
private:
std::string fileIdentifier;
public:
using std::fstream::fstream;
using std::fstream::open;
~fstreamExtension();
inline void fileName (std::string&);
inline bool exists ();
inline unsigned long long fileSize();
};
#endif
fstreamExtension.cpp:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include "fstreamExtension.h"
inline void fstreamExtension::fileName (std::string& __fileIdentifier)
{
fileIdentifier = __fileIdentifier;
}
inline bool fstreamExtension::exists ()
{
if (FILE *file = fopen(fileIdentifier.c_str(), "r"))
{
fclose(file);
return true;
}
else
return false;
}
inline unsigned long long int fstreamExtension::fileSize()
{
if(exists())
{
std::ifstream tempStream(fileIdentifier.c_str(), std::ios::ate | std::ios::binary);
unsigned long long int __size = tempStream.tellg();
tempStream.close();
return __size;
}
else return 0;
}
fstreamExtension::~fstreamExtension()
{
std::fstream::close();
std::cout << "stream closed";
}
當此code
在main
文件中實現為:
#include <iostream>
#include <fstream>
#include "fstreamExtension.h"
int main()
{
string s = "QBFdata.txt";
fstreamExtension fs(s.c_str(), ios::in | ios::binary);
fs.fileName(s); //error
cout << fs.fileSize(); //error
}
當我調用函數filename()
和fileSize()
時,出現linker
error
。
codeblocks
產生以下錯誤:
未定義對fstreamExtension :: fileName(std :: string&)的引用
感謝您的幫助,請提出是否需要任何結構更改的建議。
從函數聲明和定義中刪除inline
以修復鏈接器錯誤。
inline
對於頭文件中定義的功能有意義。 對於其他地方定義的函數, inline
使其無法用於其他翻譯單元,從而導致您觀察到鏈接器錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.