【问题标题】:C++ variables passed to constructor are not being passed correctly传递给构造函数的 C++ 变量未正确传递
【发布时间】:2021-02-05 22:10:46
【问题描述】:

我只是想在 C++ 中设置一些简单的类。我正在尝试创建一个接受价格(双)、数量(int)和样式(std::string)的订单类型

这是我的订单。h

#ifndef ORDER_H
#define ORDER_H

#include <string>
#include <iostream>


class Order {
    private:
        double limit_price;
        int quantity;
        std::string style;
    public:
        Order();
        Order(double price, int quantity, std::string style);

        void print_price();
        void print();
};
#endif

我在 order.cpp 中的实现。

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


Order::Order(){
    limit_price = 0;
    quantity = 0;
    style = "bid";
}


Order::Order(double price, int quantity, std::string style){
    limit_price = price;
    quantity = quantity;
    style = style;
}

void Order::print_price(){
    std::cout << "limit_price = " << limit_price << std::endl;
}

void Order::print(){
    std::cout << style << " " << quantity << "@" << limit_price << std::endl;
}

这是我的简单测试代码。

#include "order.cpp"
#include <iostream>
#include <string>

int main(){

    Order null_order = Order();
    Order order = Order(12.3, 2, "bid");

    null_order.print();
    order.print();

    return 0;
}

但是,由于我不明白的原因,当我运行时,我运行我的测试文件,而不是获取

bid 0@0
bid 2@12.3

正如我所料,我得到了类似以下的内容。

bid 0@0
 -1722935952@12.3

每次运行时大的负数都会发生变化。

【问题讨论】:

  • 编译我只是使用命令g++ tester.cpp -o tester 其中tester.cpp 是我的测试文件的名称
  • quantity = quantity; 你认为这会做什么?为什么你认为它会这样做而不是别的?
  • #include "order.cpp" 是一个禁忌。包含头文件(.h)并编译和链接 cpp 文件。
  • 你会发现很遗憾很少教的Member Initializer List 对解开这个烂摊子非常有帮助。

标签: c++ string class cout


【解决方案1】:

在您的构造函数中,参数名称会影响成员:

Order::Order(double price, int quantity, std::string style){
    limit_price = price;
    quantity = quantity;
    style = style;
}

你觉得quantity 在第二行是什么?为什么左手边的东西和右手边的不一样?

quantity指的是参数。

您可以在成员前面加上this-&gt; 以消除歧义,但这并不常见。在这种情况下,最好重命名它们中的任何一个。

无论如何,您应该初始化成员而不是在构造函数的主体中分配。在执行构造函数的主体之前初始化成员。初始化成员的一种方法是成员初始化器列表:

Order::Order(double p, int q, std::string s) : limit_price(p),quantity(q),style(s)
{ /* empty body */ }

并且因为在初始化列表中没有歧义的危险,我们可以为参数使用与成员相同的名称:

Order::Order(double limit_price, int quantity, std::string style) : limit_price(limit_price),quantity(quantity),style(style)
{}

【讨论】:

  • 我想知道是否有任何关于初始化列表的快捷方式的建议,其中参数与成员具有相同的名称。
  • @Barmar:我认为 C++ 中没有。在 C# 中有一个“记录类型”的提议,它将自动存储所有构造函数参数。它们被添加到编译器的技术预览版中,在发布之前再次删除(我认为是 5.0?),并且看起来将成为下一个版本 (9.0) 的一部分
  • @Barmar hm 不确定是否值得增加复杂性。构造函数的一种特殊情况的新语法。另一方面,它是一条相当常见的三重重复线。
  • 这是一个特例,也是一个常见的情况。我可以想象像: () 这样的语法。
  • @Barmar 实际上这是一个有趣的想法。初始化顺序总是正确的,消除错误的一个来源
猜你喜欢
  • 2021-05-15
  • 2012-01-12
  • 2020-01-16
  • 2011-09-05
  • 2016-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多