为什么我在每一次实例化对象时,生成的对象都是同一属性的??
//以下是test.cpp
#include <stdlib.h>
#include <iostream>
#include <string>
#include <time.h>
#include "Cat.h"
using namespace std;
void check(int num);
int main(void)
{
srand((unsigned)time(NULL));
int num = rand() % 7 + 1;
check(num);
system("pause");
return 0;
}
void check(int num)
{
int gray = 0;
int brown = 0;
int black_brown = 0;
int black_green = 0;
int black_blue = 0;
//??????为何每一次实例化对象生成的对象都是同一属性?
for (int i = 0;i < num;i++)
{
Cat *p = new Cat;
if (p->getSkinColor()=="gray")
{
gray++;
}
if (p->getSkinColor()=="brown")
{
brown++;
}
if (p->getSkinColor()=="black")
{
if (p->getEyeColor()=="brown")
{
black_brown++;
}
if (p->getEyeColor() == "green")
{
black_green++;
}
if (p->getEyeColor() == "blue")
{
black_blue++;
}
}
cout << "这是一只" << p->getSkinColor() << "皮肤" << p->getEyeColor() << "眼睛的猫" << endl;
}
if (gray>brown&&brown>0)
{
cout << "它们将会打架~~~~~" << endl;
}
else if (black_brown>0&&black_green>0&&black_blue>0)
{
cout << "它们将会打架~~~~~" << endl;
}
else
{
cout << "它们将不会打架~~~~~" << endl;
}
}
//一下是Cat.h文件
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
class Cat
{
public:
Cat();
void setSkinColor(string color) ;
string getSkinColor() ;
void setEyeColor(string color);
string getEyeColor();
~Cat();
private:
string skin_color;
string eye_color;
};
//以下是Cat.cpp文件
#include <iostream>
#include <stdlib.h>
#include <string>
#include <time.h>
#include "Cat.h"
using namespace std;
Cat::Cat()
{
string color[][3] = { { "black" ,"gray","brown" } ,{ "green" ,"blue","brown" } };
//string color[1][3] = { "green" ,"blue","brown" };
string c[2];
srand((unsigned)time(NULL));
for (int i=0;i<2;i++)
{
int j = rand() % 3;
c[i] = color[i][j];
}
skin_color = c[0];
eye_color = c[1];
}
void Cat::setSkinColor(string color)
{
skin_color = color;
}
void Cat::setEyeColor(string color)
{
eye_color = color;
}
string Cat::getSkinColor()
{
return skin_color;
}
string Cat::getEyeColor()
{
return eye_color;
}
Cat::~Cat()
{
}