![](/img/trans.png)
[英]undefined reference error while calling a function from user defined header file and it's implementation is in .cpp file
[英]undefined reference to function declared in header and implemented in cpp file
我正在使用一些基本的C ++代碼,這些代碼使用兩個cpp文件(Main.cpp和CarbStore.cpp)和一個標頭(CarbStore.h)。 在我的標頭中,我聲明了一個函數,稍后在CarbStore.cpp中實現。 當我從Main.cpp調用函數時,它給了我錯誤:
Main.cpp:17:對`CarbStore :: CalcCarbs的未定義引用(unsigned char,unsigned char,unsigned char,float,unsigned int,std :: __ cxx11 :: basic_string,std :: allocator>)const'
我的文件包含以下代碼:
Main.cpp的
#include <iostream>
#include <cstdint>
#include <cmath>
#include <ctime>
#include "CarbStore.h"
void CarbCalculator()
{
CarbStore carb;
carb.CalcCarbs(10, 11, 12, 0.1, 100, "test");
}
int main(int,char *[])
{
CarbCalculator();
std::cout << "Press enter to exit." << std::endl;
std::cin.get();
}
CarbStore.cpp
#include "CarbStore.h"
#include <iostream>
void CalcCarbs(unsigned char r, unsigned char b, unsigned char g, float bounciness, unsigned int price, std::string manufacturer)
{
//use values at later state
return;
}
CarbStore.h
#ifndef CARBSTORE_H
#define CARBSTORE_H
#include <vector>
class CarbStore
{
public:
void CalcCarbs(unsigned char r, unsigned char b, unsigned char g, float bounciness, unsigned int price, std::string manufacturer) const;
};
#endif
正如評論中已經提到的,以下內容
void CalcCarbs(unsigned char r, unsigned char b, unsigned char g, float bounciness, unsigned int price, std::string manufacturer)
{
//use values at later state
return;
}
未實現的成員函數CalcCarbs
的CarbStore
,而是它聲明並定義了一個新的免費功能稱為CalcCarbs
。 要實現成員函數,您需要告訴編譯器函數定義應屬於哪個類。 這是通過在函數名稱前附加類名稱和雙冒號來完成的:
void CarbStore::CalcCarbs(unsigned char r, unsigned char b, unsigned char g, float bounciness, unsigned int price, std::string manufacturer)
{
//use values at later state
return;
}
簽名也必須匹配。 在CarbStore
您聲明了const
,但在實現中並未聲明。 要更正它:
void CarbStore::CalcCarbs(unsigned char r, unsigned char b, unsigned char g, float bounciness, unsigned int price, std::string manufacturer) const
{
//use values at later state
return;
}
但是,您真正想要一個帶有空返回值的const
成員函數的可能性很小,因為這樣的函數只能通過修改全局變量或執行IO才能產生持久的效果。
此外,但與此特定錯誤消息無關:
CarbStore
您使用的是std::string
,因此您需要#include<string>
。 另一方面,我沒有看到任何std::vector
,因此#include<vector>
似乎是不必要的(除了Main.cpp
iostream
之外,其他所有內容都包括在內)。 return;
函數主體的末尾對於void
函數也void
。 main
不使用命令行參數,則還可以給它簽名int main()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.