【发布时间】:2016-06-07 17:49:17
【问题描述】:
#include <iostream>
using namespace std;
class Item
{
private:
string name;
int power;
int durability;
public:
Item(string n, int p, int d);
void Describe() const;
~Item();
};
Item::Item(string n, int p, int d)
{
name = n; power = p; durability = d;
}
我也无法显示此功能...我该如何调用它?
void Item::Describe() const
{
cout << name << " (power=" << power << ", durability=" << durability << ")\n";
}
Item::~Item()
{
cout << "** Item " << name << " is being deallocated." << endl;
}
class Warrior
{
private:
string name;
int level;
string profession;
Item *tool;
public:
Warrior(string n, int l, string p);
Warrior(const Warrior& otherObj);
void GiveTool(string toolName, int toolPower, int toolDurability);
void Describe() const;
};
Warrior::Warrior(string n, int l, string p)
{
name = n;
level = l;
profession = p;
}
Warrior::Warrior(const Warrior& otherObj)
{
if(otherObj.tool != NULL)
this->tool = new Item(*(otherObj.tool));
else
this->tool = NULL;
}
我认为问题似乎在这里...... 所以这就是我想要做的。
如果 tool 为 NULL 意味着战士没有工具给他一个工具。 但是,如果他确实有工具,请解除分配工具变量 而是给他这个工具。
void Warrior::GiveTool(string toolName, int toolPower, int toolDurability)
{
if(tool == NULL)
this->tool = new Item(toolName,toolPower,toolDurability);
else
{
cout << name << "'s existing tool is being replaced." << endl;
delete tool;
this->tool = new Item(toolName,toolPower,toolDurability);
}
}
那么我将如何显示新分配的工具... 它会像我在这里所做的那样只是“工具”吗? 因为当我运行程序时,它会显示地址而不是内存。
void Warrior::Describe() const
{
cout << name << " is a level " << level << " " << profession << endl;
if(tool != NULL)
{
cout << "His tool is: ";
cout <<tool;
cout << "....";
}
else
{
cout << "No tool\n";
}
}
int main()
{
Warrior a("Stephen Curry", 30, "NBA Player");
a.GiveTool("Basketball", 50, 20);
a.Describe();
a.GiveTool("Football", 10, 20);
a.Describe();
}
我认为输出应该是这样的:
斯蒂芬库里是一名 30 级的 NBA 球员
他的工具是:篮球
Stephen Curry 的现有工具正在被替换。
项目篮球正在被释放。
斯蒂芬库里是一名 30 级的 NBA 球员
他的工具是:足球
提前感谢您!任何事情都会有所帮助。我对这个编程很陌生 世界,在阅读我的代码时请记住这一点...... 再次感谢任何帮助谢谢!
【问题讨论】:
-
您的代码有几个问题。您的复制构造函数缺少复制所有成员。在您的 3 参数构造函数中,您未能将
tool初始化为 NULL。您缺少Warrior的赋值运算符,并且可能还有更多错误。为什么要参与指针?只需在Warrior类中添加Item tool;,删除错误的复制构造函数,让GiveTool执行一个简单的tool = Item(tool, whatever)(没有new),你的大部分问题都会消失。 -
@PaulMcKenzie 这是为了分配任务。我需要使用指针。其中涉及动态分配和释放
-
@Ares -- 许多人参加 C++ 课程,他们的作业要求他们使用对象,而不是指针。因此,对于我们这里的许多人来说,仅仅因为它是一个赋值并不意味着“使用指针”。