当我尝试编译以下代码时,出现此错误:
obj\Debug\main.o||In function `main':|
C:\Users\dmarr\Documents\CSharper\Dallas\CPlusPlus\WHYGODWHYCB\main.cpp|16|undefined reference to `bag::bag()'|
||=== Build finished: 1 errors, 0 warnings ===|
起初,我将 bag.h 和 bag.cpp 作为两个单独的文件——这里的许多与“未定义引用”相关的答案都建议将 .cpp 文件的内容移动到 .h 文件中——所以我这样做了。但是,我在编译时仍然遇到上述错误。
aItem.cpp:
//aItem .cpp implementation file
#include "aItem.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
//setting this up default
aItem::aItem()
{
m_itemName = "Default Name";
m_itemType = "Default Type";
m_damage = 9001;
}
void aItem::setName(string name)
{
m_itemName = name;
}
void aItem::setType(string type)
{
m_itemType = type;
}
void aItem::setDamage(int damage)
{
m_damage = damage;
}
string aItem::getName()
{
return m_itemName;
}
string aItem::getType()
{
return m_itemType;
}
int aItem::getDamage()
{
return m_damage;
}
aItem.h:
#ifndef AITEM_H_INCLUDED
#define AITEM_H_INCLUDED
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class aItem
{
public:
//constructor
aItem();
//Methods
void ItemCreate(string itemName, string itemType, int damage);
void setName(string name);
void setType(string type);
void setDamage(int damage);
string getName();
string getType();
int getDamage();
private:
string m_itemName;
string m_itemType;
int m_damage;
};
#endif // AITEM_H_INCLUDED
袋子.h:
#ifndef BAG_H_INCLUDED
#define BAG_H_INCLUDED
#include "aItem.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class aItem;
class bag : public aItem
{
public:
//constructor
bag();
//methods
//void delItem(aItem aitem);
void addItem(aItem var)
{
m_items.push_back(var);
}
void bagList()
{
for( vector<aItem>::size_type index = 0; index < m_items.size(); index++ )
{
//Makes a numerical list.
cout << "Item " << index + 1 << ": " << m_items[index].m_itemName << endl;
index+= 1;
}
}
private:
vector<aItem> m_items;
};
#endif // BAG_H_INCLUDED
...最后,main.cpp:
// WHYGODWHY.cpp : Defines the entry point for the console application.
//
#include "aItem.h"
#include "bag.h"
#include <iostream>
using namespace std;
int main()
{
aItem woodSword;
woodSword.setName("Wooden Sword");
woodSword.setDamage(3);
woodSword.setType("WPN");
bag inventory;
inventory.addItem(woodSword);
inventory.bagList();
cout << "Name: " << woodSword.getName() << endl;
cout << "Type: " << woodSword.getType() << endl;
cout << "Damage: " << woodSword.getDamage() << endl;
//cout << "Inv: " <<
int pause = 0;
cout << "Pause!";
cin >> pause;
return 0;
}