【问题标题】:Class variables getting changed somehow类变量以某种方式改变
【发布时间】:2017-01-26 00:19:38
【问题描述】:

我正在为类编写一些类,由于某种原因,我的私有变量在构造函数设置它们之后以某种方式发生了变化。在我的代码中,每个点实例的 x,y 值都被保存为非常小的数字,根本不接近它们的实际值。当我在构造函数运行后计算出一些存储的值时,这些值是正确的,但是当调用我的斜率或长度函数时,它们被传递了完全错误的值,导致长度为 0,斜率为“nan”。知道为什么会这样吗?

LineSegment.hpp

#include "Point.hpp"

#ifndef LineSegment_hpp
#define LineSegment_hpp

class LineSegment
{
private:
    Point endp1;
    Point endp2;

    double x_1;
    double x_2;
    double y_1;
    double y_2;

public:
    LineSegment(Point p1, Point p2);
    //SET-METHODS
    void setEnd1(Point p1);
    void setEnd2(Point p2);

    //get-methods
    Point getEnd1();
    Point getEnd2();

    //calculations
    double slope();
    double length();
};
#endif

LineSegment.cpp

  #include "LineSegment.hpp"
    LineSegment::LineSegment(Point p1, Point p2)
    {
        double x_1 = p1.getXCoord();
        double y_1 = p1.getYCoord();
        setEnd1(p1);

        double y_2 = p2.getYCoord();
        double x_2 = p2.getXCoord();
        setEnd1(p2);
    }

//set functions
void LineSegment::setEnd1(Point p1)
{
    Point endp1 =  p1;
}

void LineSegment::setEnd2(Point p2)
{
    Point endp2 =  p2;
}

//get-methods
Point LineSegment:: getEnd1()
{
    return endp1;
}

Point LineSegment:: getEnd2()
{
    return endp2;
}

//calculations

double LineSegment::slope()
{
    return (y_2-y_1)/(x_2-x_1);
}

double LineSegment::length()
{
    return endp1.distanceTo(endp2);
}

Main.cpp

#include "Point.hpp"
#include "LineSegment.hpp"
#include <iostream>

int main()
{
    Point p1(-1.5, 0.0);
    Point p2(1.5, 4.0);
    double dist = p1.distanceTo(p2);

    LineSegment ls1(p1, p2);

    double length = ls1.length();
    std::cout << length << std::endl;
    double slope = ls1.slope();
    std::cout << slope << std::endl;
}

【问题讨论】:

  • 删除所有垂直空白,这会使您的代码不可读。

标签: c++ class variables


【解决方案1】:

您的设置器设置本地 变量而不是设置类成员。

由于某种原因,您在 setter 方法中声明了与类成员同名的局部变量。局部变量隐藏类成员。您执行的所有修改都会修改这些局部变量,而不会影响类成员。

例如这里

void LineSegment::setEnd1(Point p1)
{
    Point endp1 = p1;
}

当您打算(我想)设置类成员时,为什么要声明局部变量 Point endp1

【讨论】:

  • 我被要求有一个获取和设置端点的功能。即使我不使用它们,当他包含自己的 main() 时,老师也可能会使用它们。我没有意识到在变量前面包含数据类型本质上是声明新的!脑洞大开,谢谢!!
猜你喜欢
  • 2010-09-08
  • 2021-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-13
  • 1970-01-01
相关资源
最近更新 更多