学习c++数据结构

Learning C++ in Data Structures.

本文关键字:数据结构 c++ 学习      更新时间:2023-10-16

这很简单,但我不知道我做错了什么。

下面是我的代码: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。