【问题标题】:Unable to pass variable from my .cpp to .h class?无法将变量从我的 .cpp 传递到 .h 类?
【发布时间】:2020-08-01 04:09:46
【问题描述】:

我有以下设置

方形.h

#ifndef square_h
#define square_h
#include "Shape.h"
using namespace std;

class Square : public Shape
{
     public:
              Point * points = nullptr;
              int minX = 0;
              int maxX = 0;
              
              ...

              void getMinMax(Point *points, int minX, maxX)
}
# endif

Square.cpp

...

void Square :: getMinMax(Point *points, int minX, int maxX)
{
    this->minX = points[3].x;
}

...

string Square :: toString()
{
     cout << "Minimum X : " << minX << endl;
}

main.cpp

...

for(size_t i = 0; i < shapes.size(); i++)
{
    cout << shapes[i]->toString();
}

基于上面的 sn-p 代码,我在 square.cpp 中有一个函数,我试图将 minX 传递回 .h minX 变量。这个想法是允许这个 minX 在 .h 文件中声明的其他函数中使用。

但是,当我在其他函数中 cout minX 时,我总是得到 0,即使我的 points[3].x 具有 > 0。

通过引用我的minX 到我的头类变量 minX 的正确方法是什么?

注意:.cpp 函数只是一个测试,看看我的值是否传递到 .h minX

【问题讨论】:

  • 我认为我们需要查看更多代码,我认为您发布的任何内容都没有问题。
  • 你能把minimal reproducible example放在一起吗?我不清楚问题是什么。您显示的函数应该更改该对象中minX 成员的值。很难说我们看不到的代码中可能发生了什么。
  • 我没有看到问题发布更多代码。
  • 您好,我添加了更多与问题相关的代码 sn-p(抱歉,此时我无法生成可重现的示例)。当我运行程序并且 main.cpp 运行 for 循环到 cout 时,最小 X 将始终为 0。
  • 你设置了minX,但输出minY,对吗?你怎么称呼getMinMax?为什么它被称为getMinMax,而它所做的只是set 单个成员变量?真的,请创建一个minimal reproducible example 向我们展示。还要花点时间刷新the help pages,拿SOtour,读How to Ask,还有this question checklist

标签: c++ pointers pass-by-reference


【解决方案1】:

toString() 方法不返回任何内容。它应该返回字符串而不是将其写入cout。当您执行cout &lt;&lt; shapes[i]-&gt;toString(); 时,您将结果写入cout

string Square :: toString()
{
    std::stringstream ret;
    ret << "Minimum X : " << minY << endl;
    return ret.str();
}

【讨论】:

    猜你喜欢
    • 2020-02-25
    • 2014-03-28
    • 2018-03-23
    • 1970-01-01
    • 2014-05-11
    • 1970-01-01
    • 1970-01-01
    • 2020-09-29
    • 2018-09-09
    相关资源
    最近更新 更多