在函数调用中将值更改为随机数?

时间:2014-11-14 03:48:31

标签: c++

#include <iostream>
#include "Shapes.h"

int main()
{
    //variables
    int height = 0;
    int width = 0;

    Rectangle rect = Rectangle();
    Triangle tran = Triangle();
    Square sqar = Square();

    std::cout << "What is the width of the shape? ";
    std::cin >> width;
    std::cout << "What is the height of the shape?";
    std::cin >> height;
    rect.set_lengths(width, height);
    std::cout << "If the shape is a triangle, the area is " << tran.area() << "." << std::endl;
    std::cout << "If the shape is a rectangle, the area is " << rect.area() << "." << std::endl;
    std::cout << "If the shape is a square, the area is " << sqar.areaByWidth() << " by the width value," << std::endl;
    std::cout << "and " << sqar.areaByHeight() << " by the height value." << std::endl;
    system("pause");
}

标题文件:

//Our base class
class Shape 
{
protected:
    int width, height, shapes = 0;
public:
    void set_lengths(int width, int height)
    {
        width = width; height = height;
    }
};

//Rectangle is a shape
class Rectangle : public Shape 
{
public:
    Rectangle()
    {
        std::cout << "Created a rectangle!\n";
        shapes = shapes + 1;
    }
    ~Rectangle()
    {
        shapes = shapes - 1;
    }

    int area()
    {
        return width * height;
    }
};

//Triangle is a shape
class Triangle : public Shape 
{
public:
    Triangle()
    {
        shapes = shapes + 1;
        std::cout << "Created a triangle!\n";
    }
    ~Triangle()
    {
        shapes = shapes - 1;
    }
    int area()
    {
        return width * height / 2;
    }
};

//Square is a shape
class Square : public Shape 
{
public:
    Square()
    {
        shapes = shapes + 1;
        std::cout << "Created a square!";
    }
    ~Square()
    {
        shapes = shapes - 1;
    }
    int areaByWidth()
    {
        return width * width;
    }
    int areaByHeight()
    {
        return height * height;
    }
};

当我设置值时,它工作正常(在visual studio调试器中显示正确的值),但是当我调用area()时它会带回-846388729或类似的东西?为什么值被重置?我一直在墙上撞了几个小时。对于像我这样的新手而言似乎是一个常见的问题,但我不理解其他解决方案:(

2 个答案:

答案 0 :(得分:2)

函数set_lengths没有正确设置成员变量,只需将值设置回函数参数。

变化

void set_lengths(int width, int height)
{
    width = width; height = height;
}

void set_lengths(int width, int height)
{
    this->width = width; this->height = height;
}

或者为了一个好习惯改变成员变量的名称:

int width_, height_, shapes_;
void set_lengths(int width, int height)
{
    width_ = width; 
    height_ = height;
}

答案 1 :(得分:0)

因为widthheight没有被启动。

enter image description here

将行更改为:

int i = 0, j = 0, k = 0;

此外,您只需设置rect对象的尺寸,而不是三角形或正方形。