Скажем, у вас было два класса «TwoDice» и «Die». Вы хотите, чтобы два объекта Die всегда были частью экземпляра TwoDice, поэтому вы создаете два объекта Die в конструкторе.Как использовать объект, созданный в конструкторе
TwoDice::TwoDice()
{
Die die1;
Die die2;
}
Затем вы вызываете метод rollDice объекта TwoDice, который, в свою очередь, вызывает каждый отдельный метод броска Die.
bool TwoDice::rollDice()
{
faceValue1 = die1.roll();
faceValue2 = die2.roll();
}
В настоящее время проблема в том, что, когда я поставил его так, die1 и die2 не определены, которые имеют смысл, потому что это только локальные переменные внутри этого конструктора. Однако, когда я создал die1 и die2 специально определенные частные переменные для класса TwoDice, я получил несколько ошибок компиляции. Есть ли способ сделать эти два объекта Die общедоступными, чтобы другие методы могли получить к ним доступ?
Вот файл TwoDice.cpp:
// TwoDice.cpp: TwoDice class method definitions
#include "stdafx.h"
#include "time.h"
#include "TwoDice.h"
#include "Die.cpp"
#include "Die.h"
#include <cstdlib>
#include <iostream>
using namespace std;
TwoDice::TwoDice(void)
{
Die die1;
Die die2;
}
TwoDice::TwoDice(int d1, int d2)
{
Die die1(d1);
Die die2(d2);
}
void TwoDice::rollDice(void)
{
die1.roll();
die2.roll();
}
void TwoDice::getFaceValueDieOne(void)
{
faceValueDie1 = die1.getFaceValue();
}
void TwoDice::getFaceValueDieTwo(void)
{
faceValueDie2 = die2.getFaceValue();
}
bool TwoDice::isMatchingPair(void)
{
if(faceValueDie1 == faceValueDie2)
{
return true;
}
else
{
return false;
}
}
bool TwoDice::isSnakeEyes(void)
{
if(faceValueDie1 == 1 && faceValueDie2 == 1)
{
return true;
}
else
{
return false;
}
}
void TwoDice::display(void)
{
cout << "Die 1 = " << faceValueDie1 << endl;
cout << "Die 2 = " << faceValueDie2 << endl;
}
int TwoDice::getValueOfDice()
{
return faceValueDie1 + faceValueDie2;
}
А вот файл TwoDice.h:
// TwoDice.h: class definition file
#pragma once
class TwoDice
{
private:
int faceValueDie1;
int faceValueDie2;
public:
TwoDice();
TwoDice(int, int);
void rollDice();
void getFaceValueDieOne();
void getFaceValueDieTwo();
bool isMatchingPair();
bool isSnakeEyes();
void display();
int getValueOfDice();
};
Вот Die.cpp:
// Die.cpp: Die class method definitions
#include "stdafx.h"
#include "time.h"
#include "Die.h"
#include <cstdlib>
using namespace std;
Die::Die(void)
{
numSides = 6;
faceValue = 0;
srand((unsigned int)time(NULL));
}
Die::Die(int n)
{
numSides = n;
faceValue = 0;
srand((unsigned int)time(NULL));
}
int Die::roll()
{
faceValue = rand()%numSides + 1;
return faceValue;
}
int Die::getFaceValue()
{
return faceValue;
}
Вот Die. h:
// Die.h: class definition file
#pragma once
class Die
{
private:
int numSides;
int faceValue;
public:
Die();
Die(int n);
int roll();
int getFaceValue();
};
Вы должны поместить код с переменными-членами, по крайней мере, так как этот код просто недействительным в его дизайне. – MasterPlanMan
Почему экземпляры Die не являются членами vars? –
#include "Die.cpp": зачем вам это делать? – SirDarius