在类中返回错误的数据

时间:2015-12-13 23:47:11

标签: c++

我正在学习课程并且表现良好,直到我尝试打印出我的Tom Animal课程。

它给了我一个输出:

  

高1246009934厘米,体重0公斤。   动物被摧毁

与我返回的Fred Animal类相反:

  弗雷德身高33厘米,体重10公斤。动物弗雷德被摧毁

这是我的代码:

#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <cstdlib>
#include <unistd.h>
using namespace std;

class Animal {
private:
    int height;
    int weight;
    string name;

    static int numOfAnimals;

public:
    int getHeight(){ return height;}
    int getWeight(){ return weight;}
    string getName(){ return name;}
    void setHeight(int cm){ height = cm;}
    void setWeight(int kg){ weight = kg; }
    void setName(string animalName){name = animalName;}
    void setAll(int, int, string);

    Animal(int, int, string);

    ~Animal();

    Animal();

    static int getNumberofAnimals() {return numOfAnimals;}

    void toString();
};

int Animal::numOfAnimals = 0;

void Animal::setAll(int height, int weight, string name){
    this -> height = height;
    this -> weight = weight;
    this -> name = name;
    Animal::numOfAnimals++;
}

Animal::Animal(int height, int weight, string name) {
}

Animal::~Animal(){
    cout << "Animal " << this -> name << " destroyed" << endl;
}

Animal::Animal(){
    Animal::numOfAnimals++;
}

void Animal::toString(){
    cout << this -> name << " is " << this -> height << " cms tall and " << this -> weight << " kgs in weight" << endl;
}

int main()
{
    Animal Fred;

    Fred.setHeight(33);
    Fred.setWeight(10);
    Fred.setName("Fred");

    cout << Fred.getName() << " is " << Fred.getHeight() << " cms tall and " << Fred.getWeight() << " kgs in weight." << endl;

    Animal Tom(36, 15, "Tom");
    cout << Tom.getName() << " is " << Tom.getHeight() << " cms tall and " << Tom.getWeight() << " kgs in weight." << endl;

    return 0;
}

任何人都可以帮助我。感谢

2 个答案:

答案 0 :(得分:1)

您的构造函数不执行任何操作,FredTom的类成员未初始化。

请改用:

Animal::Animal() {
    SetAll(0, 0, "");
}

Animal::Animal(int height, int weight, string name) {
    SetAll(height, weight, name);
}

答案 1 :(得分:0)

有3个问题:

1)对于默认构造函数,您无法初始化Animal的成员变量。

Animal::Animal()
{
    Animal::numOfAnimals++;
}

应该更改它以提供某种默认值:

Animal::Animal()
{
    SetAll(0,0,"");
}

2)在非默认构造函数中,您无法初始化成员。

Animal::Animal(int height, int weight, string name) 
{
}

应该改为:

Animal::Animal(int height, int weight, string name) 
{
   SetAll(height, weight, name);
}

3)在复制构造的情况下,您的代码将无法更新动物数量:

Animal Fred;
Animal Fred2 = Fred;
cout << Animal::getNumberofAnimals();

您会看到输出为1,即使显然有2个Animal对象已创建。

要解决此问题,您需要有一个复制构造函数:

Animal::Animal(const Animal& rhs)
{
   SetAll(rhs.height, rhs.width, rhs.name);
}