很抱歉这个问题措辞如此尴尬,因为我不知道该怎么问。在任何情况下,我都有一个名为“aItem”的类的实现文件和头文件,其中包含 aItem 对象的向量。
在名为“bag”的第二个文件中,我希望能够列出上述向量的所有元素。我最初将“包”分为头文件和实现文件,但编译器对“未声明的引用”表示不满意,直到我合并这两个文件。无论如何,该部分正在工作。
我希望 bag.h(更具体地说是 addItem 函数)能够访问已创建项目的 m_itemName 变量。
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;
}
编辑:这是错误消息:C:\Users\dmarr\Documents\CSharper\Dallas\CPlusPlus\WHYGODWHYCB\aItem.h||在成员函数 'void bag::bagList()':| C:\Users\dmarr\Documents\CSharper\Dallas\CPlusPlus\WHYGODWHYCB\aItem.h|28|错误:'std::string aItem::m_itemName' 是私有的| C:\Users\dmarr\Documents\CSharper\Dallas\CPlusPlus\WHYGODWHYCB\bag.h|32|错误:在此上下文中| ||=== 构建完成:2 个错误,0 个警告 ===|