我有两个名为PowerballLottery
和PowerballTicket
的课程。在PowerballLottery
内部有一个名为quickPick
的成员函数,它应该选择6个随机有效的整数并将它们存储在PowerballTicket
中。 6个整数mBall1, mBall2, mBall3, mBall4, mBall5 and mPowerball
在PowerballTicket
内初始化,而班级PowerballTicket
应存储由quickPick
生成的6个随机整数的值。如何将PowerballTicket
内的6个int的对象传递给PowerballLottery
,以便quickPick可以修改它们?
答案 0 :(得分:1)
无需将数字传递给quickPick()
。该函数只能生成一个PowerballTicket
对象并将其返回。然后,将新值分配给旧的licket对象。
struct PowerballTicket
{
int mBall1 = 0;
int mBall2 = 0;
int mBall3 = 0;
int mBall4 = 0;
int mBall5 = 0;
int mPowerBall = 0;
PowerballTicket(int b1, int b2, int b3, int b4, int b5, int pb)
: mBall1(b1),
mBall2(b2),
mBall3(b3),
mBall4(b4),
mBall5(b5),
mPowerBall(pb)
{
}
};
class PowerballLottery
{
public:
PowerballTicket quickPick()
{
// generate numbers
// then create a PowerballTicket object and return it
return PowerballTicket(1, 2, 3, 4, 5, 1000);
}
};
如果您想更改PowerballTicket
对象,只需执行以下操作:
PowerballTicket ticket;
PowerballLottery lottery;
ticket = lottery.quickPick();
答案 1 :(得分:0)
让PowerballLottery成为PowerballTicket的成员
答案 2 :(得分:0)
通常情况下,您不会将变量传递给其他类,但可能
如果您宣布彩票为朋友"对于Ticket,它可以访问它的成员,即使它们是私有的
看看这个例子:
#include <iostream>
class changer;
class fixed {
friend class changer;
public:
fixed(int x) : m_x(x) { } ;
int get() { return m_x; };
private:
int m_x;
};
class changer
{
public:
void change(fixed& item, int new_value);
};
void changer::change(fixed& item, int new_value)
{
item.m_x = new_value;
}
int main() {
fixed one(1);
changer two;
std::cout << one.get() << "\n";
two.change (one, 2);
std::cout << one.get() << "\n";
return 0;
}
将变换器类声明为朋友,因此可以用它来更改其成员;
如果你向Ticket添加一个setter函数,并为生成的数字调用它,那么在你的情况下(如果我解释你想要的东西)就容易多了
PowerballTicket::setBalls(int b1, int b2, int b3, int b4, int b5, int pb)
{
mBall1 = b1;
mBall2 = b2;
mBall3 = b3;
mBall4 = b4;
mBall5 = b5;
mPowerball = pb;
}
答案 3 :(得分:0)
使quickPick()
成为PowerBallTicket
的朋友功能,以便它可以直接访问6个成员并设置它们
答案 4 :(得分:0)
一个简单的实现如下:
PowerballTicket
(setter / getter惯用语)void setData(const Cont &data)
,或保留std::vector<int>
等容器并添加将调用push_back(someint)
的方法,并将其称为6来自PowerballLottery
的时间。PowerballLottery
,该方法将指向PowerballTicket
void (PowerballTicket *pbt) {p_pbt = pbt;}
或将其作为参考传递(PowerballTicket &pbt
)。然后修改它:p_pbt->setData
(pbt.setData
如果您使用了引用)。
#include <cstdlib> // for rand
struct Numbers
{
int field1;
int field6;
};
class Ticket
{
public:
void setData(Numbers num) { _num = num; } //movement semantic for C++11+
Numbers getData() const { return _num; }
private:
Numbers _num;
};
class Lottery
{
public:
void fillTicket(Ticket &ticket) {
Numbers num;
num.field1 = quickPick();
num.field6 = quickPick();
ticket.setData(num);
}
private:
int quickPick() { return std::rand() % 100; }
};