编译以下源代码时遇到了麻烦 [链接器错误]对'dish :: dish()'的未定义引用 [链接器错误]未定义引用'dish ::〜dish()' [链接器错误]未定义引用'dish :: ShowResult()'有人可以帮助我吗?
HEADER FILE(dish.h):
#ifndef DISH_H
#define DISH_H
class dish {
public:
dish();
dish(std::string name, std::string variety, float caloric, float price);
~dish();
static int GetN();
void SetN(int N);
static int IncrementN();
std::string GetName() const;
void SetName(std::string name);
std::string GetVariety() const;
void SetVariety(std::string variety);
float GetCaloric() const;
void SetCaloric(float caloric);
float GetPrice() const;
void SetPrice(float price);
void Enter();
void ShowResult();
private:
std::string name;
std::string variety;
float caloric;
float price;
static int N;
};
int dish::N;
#endif
和dish.cpp:
#include <iostream>
#include <cstring>
#include "dish.h"
dish::dish()
{
dish::Enter();
}
dish::dish(std::string name, std::string variety, float caloric, float price)
{
this->name = name;
this->variety = variety;
this->caloric = caloric;
this->price = price;
}
dish::~dish()
{
}
static int dish::GetN()
{
return N;
}
void dish::SetN(int N)
{
this->N = N;
}
static int dish::IncrementN()
{
N++;
}
std::string dish::GetName() const
{
return name;
}
void dish::SetName(std::string name)
{
dish::name = name;
}
std::string dish::GetVariety() const
{
return variety;
}
void dish::SetVariety(std::string variety)
{
dish::variety = variety;
}
float dish::GetCaloric() const
{
return caloric;
}
void dish::SetCaloric(float caloric)
{
this->caloric = caloric;
}
float dish::GetPrice() const
{
return price;
}
void dish::SetPrice(float price)
{
this->price = price;
}
void dish::Enter()
{
std::cout << "\n \\*_________________________________*\\\n";
std::cout << "\n ENTER THE NAME OF DISH: ";
getline(std::cin, name);
std::cout << " ENTER THE VARIETY: ";
getline(std::cin, variety);
std::cout << " ENTER THE CALORIC CONTENT: ";
(std::cin >> caloric).get();
std::cout << " ENTER THE PRICE: ";
(std::cin >> price).get();
std::cout << "\n \\*_________________________________*\\\n";
dish::IncrementN();
}
void dish::ShowResult()
{
std::cout << "\n \\*________________________*\\\n";
std::cout << "\n THE NAME OF DISH: " << dish::GetName() << std::endl;
std::cout << " THE VARIETY: " << dish::GetVariety() << std::endl;
std::cout << " THE CALORIC CONTENT: " << dish::GetCaloric() << std::endl;
std::cout << " THE PRICE: " << dish::GetPrice() << std::endl;
std::cout << "\n \\*________________________*\\\n";
}
主要实施......
#include <cstring>
using namespace std;
#include "dish.h"
int main() {
dish a;
a.ShowResult();
return 0;
}
答案 0 :(得分:1)
您应该将dish.cpp与您的主要可执行文件链接,即在您的项目中添加dish.cpp。
答案 1 :(得分:0)
这是一个语法错误,会在dish.cpp上产生编译错误。链接错误只是其结果。
从dish.cpp中删除static
个关键字。
请记住,唯一有趣的错误几乎总是第一个。
说明:为了执行类方法,只在头文件中写入static
,而不是在.cpp中。
有关信息,但这显然不是您尝试做的事情:.cpp中的static
可用于使函数在编译单元外部不可见,但实际上是从C继承的不推荐构造。应该更喜欢匿名命名空间。