Question

I have a class that acts like a basic stack. In my member function definitions i get an error at every instance of vec. The error tells me that the expression must have a class type. What must I do to fix this issue?

class Stack{
    public:
        Stack();
        Stack & push(double & t);
        double pop() const;
        unsigned long long getElements();
    private:
        vector <double> vec[10];
        static double answer;
};

Stack::Stack(){
    answer=0;
}

Stack & Stack::push(double & t){
    vec.push_back(t);
    return *this;
}

double Stack::pop()const{
    return vec.pop_back();
}

unsigned long long Stack::getElements(){
    return vec.size();

}
Was it helpful?

Solution

There are a number of issues here, and after fixing them I got:

#include <vector>
using namespace std;
class Stack{
    public:
        Stack();
        Stack & push(double & t);
        double pop();
        unsigned long long getElements();
    private:
        vector <double> vec;
        static double answer;
};

Stack::Stack(){
    answer=0;
}

Stack & Stack::push(double & t){
    vec.push_back(t);
    return *this;
}

double Stack::pop(){
    double ret = vec.back();
    vec.pop_back();
    return ret;
}

unsigned long long Stack::getElements(){
    return vec.size();

}

The changes I made were:

  1. missing include of vector and namespace default for std.
  2. pop_back returns void - need to get the element to return first.
  3. Shouldn't declare pop as const, as it does change the vector (you can have the returned value be a const).
  4. removed [10] on vec declaration. It is not a C array.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top