我正在编写一个C++程序,它将掷骰子并掷硬币。我需要使用继承和多态性。我的虚拟功能已正确设置。在我的基类(aRandomNumberGenerator)中,我生成了一个虚函数。在main()中,我需要一个包含2个基类指针的数组,这些指针指向我的派生类(aDie和aCoin)。当我调用generate()函数时,如何知道数组中指向哪个派生类?
代码:
int main()
{
int n;
int frequency1 = 0; // count of 1s rolled
int frequency2 = 0; // count of 2s rolled
int frequency3 = 0; // count of 3s rolled
int frequency4 = 0; // count of 4s rolled
int frequency5 = 0; // count of 5s rolled
int frequency6 = 0; // count of 6s rolled
int face; // stores most recently rolled value
int numHeads = 0; // count of heads
int numTails = 0; // count of tails
int side; // stores most recently flipped value
cout << "Enter a seed number: "; // promp for user to enter a seed number
cin >> n;
cout << endl;
cout << endl;
aRandomNumberGenerator number(n);
aDie die(n, n);
aCoin coin(n, n);
aRandomNumberGenerator *games[2]; // array of 2 base class pointers
for(int i=0; i <= 2; i++)
games[i]->generate();
// output the seed number entered by the user
cout << "the seed entered is: " << die.inputSeed(n) << endl;
cout << endl;
cout << endl;
// summarize results for 600 flips of a coin
for(int counter2 = 0; counter2 < 600; counter2++)
{
side = generate();
// determine flip value 0/1 and increment appropriate counter
switch ( side )
{
case 0:
++numHeads;
break;
case 1:
++numTails;
break;
default:
cout << "can only be heads or tails";
}
}
// summarize results for 600 rolls of a die
for(int counter1 = 0; counter1 < 600; counter1++)
{
face = generate();
// determine roll value 1-6 and increment appropriate counter
switch ( face )
{
case 1:
++frequency1;
break;
case 2:
++frequency2;
break;
case 3:
++frequency3;
break;
case 4:
++frequency4;
break;
case 5:
++frequency5;
break;
case 6:
++frequency6;
break;
default:
cout << "7 doen't exist on a die!";
}
}
// output results
cout << "Heads: " << numHeads << endl;
cout << "Tails: " << numTails << endl;
cout << "1: " << frequency1 << endl;
cout << "2: " << frequency2 << endl;
cout << "3: " << frequency3 << endl;
cout << "4: " << frequency4 << endl;
cout << "5: " << frequency5 << endl;
cout << "6: " << frequency6 << endl;
cout << endl;
cout << endl;
system ("pause");
return 0;
最佳答案
使用dynamic_cast。
if (Derived1* ptr = dynamic_cast<Derived1*>(basepointer)) {
// Do something with ptr
}
但是,对于常规方法调用,您无需确定它。只需在基类上调用该方法,它将被分派(dispatch)到正确的派生类-这就是继承的目的。
编辑:对于常规的虚拟方法,您可以仅在基本指针上调用它,而不知道或不在乎Derived是什么,并且您将获得正确的函数调用。
关于c++ - 使用指针数组时如何确定指向哪个派生类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3321593/