c++ - 在函数调用时将值更改为随机数?

标签 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 或类似的东西?为什么要重置值?几个小时以来,我一直在用头撞墙。对于像我这样的新手来说似乎是一个常见问题,但我不理解这里的其他解决方案:(

最佳答案

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;
}

关于c++ - 在函数调用时将值更改为随机数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26922584/

相关文章:

c++ - C++ 中的优先级堆栈

c++ - 为什么有时将 2D 图像建模为指向指针 (T**) 的指针?

c++ - 覆盖纯虚函数的参数个数

c++ - 应该在 C++ 源代码中修改什么以生成显示函数名称和运算符的控制流图?

C++ - 如何读取系统文件

c++ - 将注册表项值读取到 std::string 的最简单方法?

c++ - std::ofstream 无法将 std::string 写入文件

c++ - 根据特定排序有效地从 map 中获取项目

c++ - 将捕获的 lambda 作为函数指针传递

c++ - HashMap 以找到添加到给定总和的一对