为了账号安全,请及时绑定邮箱和手机立即绑定

为什么我在每一次实例化对象时,生成的对象都是同一属性的??

//以下是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()
{
}

正在回答

举报

0/150
提交
取消
C++远征之模板篇
  • 参与学习       91137    人
  • 解答问题       325    个

本C++教程力求即学即会,所有知识以实践方式讲解到操作层面

进入课程

为什么我在每一次实例化对象时,生成的对象都是同一属性的??

我要回答 关注问题
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号