-3

I am learning c++, so it is hard for me to fix the errors I have when I compile this program. I am going to write a small program which can print every elements in an int array. For instance, class NumberRange has two arguments a and b, if a is 5 and b is 9, then the constructor would allocate an array and fill it with the values 5,6,7,8,9 in that order. I have my code following: the head file NumberRange.h

class NumberRange {
public:
    NumberRange(int a, int b);
    virtual ~NumberRange();
    void Print(int a, int b);
private:
    int *range_;
    int size;
};

The .cc file NumberRange.cc is:

#include <iostream>
#include "numberrange.h"
using namespace std;

NumberRange::NumberRange(int a, int b) {
    if (a > b) {
        cout << "a must be equal or less than b" << endl;
    }
}

NumberRange::~NumberRange() {
     //implementation
}

void NumberRange::Print(int a, int b) {
     this->size = b - a + 1;
     this->range_[0] = a;
     for (int i = 0; i < this->size; i++) {
         this->range_[i] = a + i;
         cout << this->range_[i] << endl;
     }
}

int main() {
    NumberRange *numberrange;
    numberrange->NumberRange (5, 9);
    numberrange->Print(5,9);
}

And I got the errors when I compile the program: cannot refer to type member 'NumberRange' in 'NumberRange' with '->' numberrange->NumberRange (5, 9);

member 'NumberRange' declared here class NumberRange {

I don't know the errors meaning and how can I fix this program? I am wondering the logic is right or not as well. Is there anyone can help me? Thank you so much.

moooeeeep
  • 31,622
  • 22
  • 98
  • 187
Xiufen Xu
  • 531
  • 1
  • 3
  • 19

1 Answers1

1
NumberRange *numberrange;
numberrange->NumberRange (5, 9);

This is not how you construct a new NumberRange. You can do either

NumberRange *numberrange = new NumberRange(5, 9);

Or better yet, avoid the superfluous memory allocation:

NumberRange numberrange(5, 9);
StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • in addition, your class has a raw pointer. You either need to implement copy construction and assignment, or delete both operators, or better yet, internally use a `std::vector` which will handle the memory management for you. *Better still* would be to just save `a` and `b`, and then print the range in `Print` rather than actually creating the range at all. – Martin Bonner supports Monica Oct 25 '16 at 08:07