Error: query for member '..' in 'this', which belongs to the non-class class - * const'

My first question is here. Please excuse me, I just logged into C ++ and started with DS. STACK!!!

My code: I think

using namespace std; typedef char stackElement; class Stack { public: stackElement *contents; //dynamically allocated: as we do not know what would be the size of our array. int top, maxSize; // current Top index in the array //max size of the array; we need it to know if the array is full Stack(int maxSize) { contents = new stackElement(maxSize); this.maxSize = maxSize; if(contents == NULL) { cout<<"Insufficient memory"; exit(1); } top = -1; } ~Stack() { delete [] contents; contents = NULL; maxSize = 0; top = -1; } bool isEmpty()const { return top < 0; } bool isFull() const { return top == maxSize - 1; } void push(stackElement element) { if(isFull()) { cout<<"STACK IS ALREADY FULL"; exit(1); } top = top + 1; contents[top] = element; } }; int main() { cout<<"STACK IMPLEMENTATION"; int i = 1; Stack s1(i); s1.push('a'); s1.push('1'); return 0; } 

I get this error:

 error: request for member 'maxSize' in 'this', which is of non-class type 'Stack* const' 
+4
source share
3 answers

If at all, you need to write this->maxSize = maxSize; since this is a pointer.

But it’s better not to write this at all and instead use a list of initializer constructors:

  explicit Stack(int m) : contents(new stackElement[m]), top(-1), maxSize(m) { // nothing else to do } 

I also added explicit so that you don't accidentally convert 5 to Stack .

You also incorrectly specified array initialization.

In addition, you do not need to verify that contents not null: when new fails, it leaves the exception, it does not return a null pointer. (This behavior does not make sense if you think about objects.)

It is very important to note that you have no more than one bare new -expression in the constructor. Everything else is a disaster with an exception-security and a sign that you need to reorganize and use resource management classes with one responsibility.


The destructor should be simple: ~Stack() { delete [] contents; } ~Stack() { delete [] contents; } Everything else is meaningless waste.


Imagine that you had to pay for each line of code that you write. Be patient, lose the source, think.

+12
source

Write

  this->maxSize = maxSize; 

instead

  this.maxSize = maxSize; 

this is a pointer type, not a reference type

+2
source

this->maxSize instead of this.maxSize

+1
source

Source: https://habr.com/ru/post/1207516/


All Articles