简体   繁体   中英

Accessing member variables from aggregated class

Just trying to get stack.cpp 's push function to increment max_size_ variable by 1.

Array.h:

template <typename T>
class Array: public BaseArray<T>
{
public:

//loads of fun code
private:
  size_t max_size_;
};

Stack.cpp:

//...even more fun code...
template <typename T>
void Stack <T>::push (T element)
{
    ArrayStack::max_size_++;

}

Stack.h:

template <typename T>
class Stack
{
public:

  Stack (void);

private:
    Array <T> ArrayStack; 
};

Error:

 error: ‘ArrayStack’ is not a class or namespace
  ArrayStack::max_size_++;

Or if I run it with just max_size_ :

template <typename T>
void Stack <T>::push (T element)
{

    max_size_++;
}

error: ‘max_size_’ was not declared in this scope
  max_size_++;

You actually can't do that without changing something. max_size_++; is a private member of ArrayStack , so you cannot change it from inside a Stack method.

Option 1 (better): Add a method to your ArrayStack that increments the value by one void incMaxSize() { max_size_++; } void incMaxSize() { max_size_++; } and call it instead

Option 2 (worse): Make the Stack class a friend of ArrayStack

Option 3 (even worse): Make the max_size_ variable public and then change the call to ArrayStack.max_size_++;

Since you made max_size_ private in your Array class you'll need to create a getter and setter to access it outside of that class. Then in your Stack class you can get the max_size_ value and save it in a local variable and then set it to 1 + it's current value to achieve max_size_++

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM