【发布时间】: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 对解开这个烂摊子非常有帮助。