Domanda

I have to write this Course class, which has elements like room, day_of_week and so on.

Each of them must be declared in a specific range for the course to be valid.

For example, day_of_week must be an integer between 1 and 6, and room must be an integer between 1 and 599.

My question is, is there a way to write my constructor so that when I initialize an object with invalid data it will not compile.

Putting it in another perspective, is there a way to declare the range of my data members in the constructor or in the class declaration.

Sorry for the long read any help is welcomed.

È stato utile?

Soluzione

No, C++ does not come with a way to do range checking, you could however implement your own number class which overloads the assignment and arithmetic operators:

#include <cassert>
template<int lower, int upper>
class RangedNumber{
public:
    RangedNumber(int value):value(value){
        test();
    }

    RangedNumber(const RangedNumber& r):value(r.value){}

    RangedNumber& operator+=(int i){
        value += i;
        test();
        return *this;
    }

    RangedNumber operator+(int i) const{
        RangedNumber r(*this);
        return r += i;
    }

    RangedNumber& operator-=(int i){
        value -= i;
        test();
        return *this;
    }

    RangedNumber operator-(int i) const{
        RangedNumber r(*this);
        return r -= i;
    }

    int get() const {
        return value;
    }
private:

    int value;
    void test(){
        if(value < lower || value >= upper) 
            throw std::out_of_range;
    }
};
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top