【问题标题】:Void inside c++ struct doesn't change one struct valuec++ 结构中的 void 不会改变一个结构值
【发布时间】:2015-12-24 13:31:25
【问题描述】:

我有这个结构

typedef struct _flight {

    FlightId flightId;

    int totalPlaces;
    int booked;

    float currentPrice;
    float initialPrice;

    void Print(int index);
    void RecalculatePrice();
    bool BookSeats(int amount);
} Flight;

这会造成麻烦,BookSeats:

bool Flight::BookSeats(int cantidad) {
   if (booked + cantidad <= totalPlaces) {
      booked = booked + cantidad;
      RecalculatePrice();
      return true;
   }
   return false;
}

当我调用 BookSeats 时,值的变化不会存储在方法的末尾(比如当你将一个变量按值传递给参数时),我尝试使用

this->booked = booked + cantidad; // but doesn't work too;

我做错了什么?我不知道是否是参考问题,但是...变量和 void 都在结构内。我不明白。

【问题讨论】:

  • 确定满足条件?
  • 如果能给出一个完整的例子就更好了?
  • Flight 的构造函数是什么样的?
  • 为什么我们需要 MCVE 的教科书示例。如果你还没有写过,那么你还没有完成调试。
  • 如果你“没有sizeof”那么就大错特错了,你实际上并不是在写C++,这一切都毫无意义。

标签: c++ function struct pass-by-reference


【解决方案1】:

在使用变量之前,您需要通过设置一个值来初始化它。 如果您的编译器接受 c++11,您可以直接在类/结构中执行,如下所示:

struct Flight {
    int booked = 0; // in-class initialization (c++11)
};

对于旧的 c++ 编译器,Flight 的构造函数应该初始化它的成员:

struct Flight {
    Flight() : booked(0) {}
    int booked; 
};

【讨论】:

  • 正如您在 cmets 中所读到的,我没有“构建”结构,而是使用 C 风格声明并设置为零。 Flight f = {0}
  • @DrkDeveloper:不要将这些信息隐藏在 cmets 中,而是生成问题的完整示例。 stackoverflow.com/help/mcve。这样,像 alex 这样的人就不会浪费时间随机猜测您的代码的作用了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-30
相关资源
最近更新 更多