学习c++数据结构
Learning C++ in Data Structures.
这很简单,但我不知道我做错了什么。
下面是我的代码:Main.cpp#include <cstdlib>
#include <iostream>
#include "throttle.h"
using namespace std;
int main(int argc, char** argv) {
throttle example;
example.shut_off();
int in = 2;
example.shift(4);
cout << "At position 2, the flow is " << example.flow() << endl;
}
throttle.h
#ifndef THROTTLE_H
#define THROTTLE_H
class throttle {
public:
//throttle();
//throttle(const throttle& orig);
//virtual ~throttle();
void shift(int amount);
bool is_on();
double flow() const;
void shut_off();
private:
int position;
};
#endif
和throttle.cpp
#include "throttle.h"
/*
throttle::throttle() {
}
throttle::throttle(const throttle& orig) {
}
throttle::~throttle() {
}
*/
//Pre:
//POST: Returns double position / total positions
double throttle::flow() const {
return double (position / 6);
}
bool throttle::is_on() {
return (flow() > 0);
}
void throttle::shift(int amount) {
position += amount;
if (amount > 6)
position = 6;
else if (amount < 0)
position = 0;
}
void throttle::shut_off() {
position = 0;
}
我的问题是不知道c++显然,但在我的主要,为什么我的shift方法不工作?用Function来代替method可能更合适。
我的逻辑是:
调用shut_off方法将位置设置为0。
调用shift方法将位置设置为4。不返回任何东西,只是将位置设置为4。但它并没有这样做。
任何精通c++的人,你还能指出其他"不好"的编码实践吗?(我知道我没有在实现中编写前置和后置条件)
当你说"不做"时,你可能是指你的心流为0?但这是意料之中的,因为你要把你的位置除以6,因为位置是整数,和6一样,你最后得到的是整数0。如果要使用双精度数,则需要在除法前将位置转换为双精度:
(double) position / 6
另一方面,您的代码将除法的结果(整数0)转换为双0。
相关文章:
- 链表,反向函数,数据结构
- 如何使用set实现无序数据结构?
- 我们可以将数据永久保存为数据结构吗?
- C++中的可变长度数组/数据结构
- 用于存储由空格分隔的字符串的 C++/C 数据结构
- 通过 NIF 从C++返回自定义数据结构
- 编译器上的策略数据结构不起作用
- 尝试构建"lock-free"数据结构C++
- 设计将引用元素移动到开头的数据结构.C++
- 在学习数据结构之前对STL有一个了解是好的吗?
- 如何解析表示树状数据结构的字符串
- 我对数据结构、双向链表有一些问题
- googletest:测试太大的数据结构
- C++中deque数据结构的大O是什么?
- 我可以使用哪种数据结构来处理这种方式
- 将文本文件解析为树状数据结构
- C++ 中具有 O(1) 搜索时间复杂度的数据结构
- 哪些存储了不完整类型的 STL 数据结构可以用作类成员?
- C++,您能否设计一种数据结构,将指针保存在连续内存中并且不会使它们失效?
- 带参数的数据结构的全局声明