【问题标题】:Accessing class object elements from a private array class C++从私有数组类 C++ 访问类对象元素
【发布时间】:2014-12-06 03:51:51
【问题描述】:

我有一个 BankAccount 类,它的一个私有成员是 BankAccount* 客户 [10]。我想将 BankAccount(string s, int a, double c, double r, double s) 类型的对象放在数组中,然后使用 getString() 访问每个单独的数据,例如使用 getString() 访问 string s 或使用 getAccountNum( )。一直在尝试很多东西,但我得到一个空白的黑匣子。如何将对象放入私有类数组中?

#include "BankAccount.h"

BankAccount::BankAccount() : customers()
{

}

void BankAccount::work()
{
string n = "name";
string* nn = &n;
BankAccount* b = new BankAccount(nn);



customers[0] = b;
go();
}

BankAccount::BankAccount(string* n)
{

name = n;
}
string BankAccount::getName()
{
return *name;
}

void BankAccount::go()
{

string st = customers[0]->getName();
cout << st << endl;
}

【问题讨论】:

  • 你的代码有更多的问题,我想我害怕看到其余的。 :)
  • BankAccount* b = new BankAccount(); b = new BankAccount(n); BankAccount a[1]; a[0] = *b; 哦,我的。
  • 你真的需要再次阅读你的 C++ 书中关于类的章节。你还没有得到它。
  • 我现在收到一个写入违规错误。我将如何正确实施?我已经为此工作了几个小时。我只想将类对象存储在数组中。
  • @WilliamWymerus - 你的代码有很多问题。这种情况的一个症状是“写作违规”。

标签: c++ arrays pointers object stack-overflow


【解决方案1】:

首先。创建银行帐户的成员变量数组。 第二。如果您不知道如何使用指针,请不要使用它。即使它不是指针类型,您仍然可以将“BankAccount”放入数组中,您仍然会得到相同的结果。

BankAccount::BankAccount() : customers()
{

}

void BankAccount::work() 
{
string n = "name";

BankAccount* b = new BankAccount(); //do thus
b = new BankAccount(n);    //dont do this('b' above will create memory leak
BankAccount a[1];    //no need to do this
a[0] = *b;  // and this
customers[0] = a;  // assign 'b' instead of 'a'

//customers 是你的BankAccount 的成员变量数组吗?只需添加设置“名称”的方法或使用此“客户[0].name = n;”您仍然可以设置其成员变量“名称” }

BankAccount::BankAccount(string n)
{
    BankAccount nn;    //don't do this
nn.name = n;    // also this
// if you want to set the value of your member variable 'name', just equate it 'name = n;'  you dont need to create new instance of 'BankAccount'.
}
string BankAccount::getName()
{
    return name;  //this is your only correct item
}

void BankAccount::go()
{
BankAccount b ;    // dobt do this
string st = b.customers[0]->getName();  // almost correct. If you want to get name of 'customer[0]' just use this 'string st = customers[0]->getName();'  or you can easily do print out 'cout << customers[0]->name << endl;'
cout << st << endl;
}

我认为您在这里遇到的问题是使用“BankAccount”实例和指针。 如果你想访问成员变量,你不需要它的新实例(如果你从新实例中获取值,输出会有所不同)。

尝试阅读 c++ 基础知识以获取更多详细信息。

我现在正在使用我的手机,如果我不能更好地解释,请原谅我。我希望它有所帮助。 我希望你能让你的代码正常工作。 它仍然需要做很多正确的工作。

【讨论】:

  • 这真的没有帮助,因为数组必须是一个指针。如果对象不是指针,则没有其他方法可以将其声明为类的私有成员。我需要知道如何使数组对象填充其类对象的元素。
  • 哈哈哈!如果您需要使用指针,请尝试学习如何使用它们。无论如何。只需将成员变量的数据类型更改为指针并将其用作指针即可。将成员变量的访问权限更改为“->”而不是“。”
  • 我让它工作了。所以感谢您指出我正确的方向;)我会投票给您,但我没有 15 或更多的代表。对不起。想知道为什么我的声望这么低?
  • 谢谢! :-) 我想你需要参与提问和回答问题来提高你的代表。
  • 刚刚添加的信息。当你使用'new'时,你必须'delete',否则会有内存泄漏。
猜你喜欢
  • 2011-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-09
  • 1970-01-01
  • 2019-06-05
  • 2020-11-26
  • 1970-01-01
相关资源
最近更新 更多