對不起,這個問題的措辭太笨拙了,因爲我不知道該怎麼提問。在任何情況下,我都有一個名爲「aItem」的類的實現文件和頭文件,其中包含一個Vector對象的向量。如何從頭文件中訪問類的私有成員?
在第二個名爲「bag」的文件中,我希望能夠列出上述向量的所有元素。我原本將「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
bag.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 | error:'std :: string aItem :: m_itemName'是private | C:\ Users \ dmarr \ Documents \ CSharper \ Dallas \ CPlusPlus \ WHYGODWHYCB \ bag.h | 32 |錯誤:在此上下文中| || ===構建完成:2個錯誤,0個警告=== |
謝謝!現在有另一個問題,但必須等待20分鐘才能發佈...>。< –