简体   繁体   English

从聚合类访问成员变量

[英]Accessing member variables from aggregated class

Just trying to get stack.cpp 's push function to increment max_size_ variable by 1.只是试图让stack.cpp的推送函数将max_size_变量增加 1。

Array.h:数组.h:

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

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

Stack.cpp:堆栈.cpp:

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

}

Stack.h:堆栈.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_ :或者,如果我只使用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.ArrayStack的私有成员,因此您不能从Stack方法内部更改它。

Option 1 (better): Add a method to your ArrayStack that increments the value by one void incMaxSize() { max_size_++; }选项 1(更好):向您的ArrayStack添加一个方法,该方法将值增加一个void incMaxSize() { max_size_++; } void incMaxSize() { max_size_++; } and call it instead void incMaxSize() { max_size_++; }并调用它,而不是

Option 2 (worse): Make the Stack class a friend of ArrayStack选项 2(更糟):Stack类成为ArrayStack的朋友

Option 3 (even worse): Make the max_size_ variable public and then change the call to ArrayStack.max_size_++;选项 3(甚至更糟):公开max_size_变量,然后将调用更改为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.由于您在 Array 类中将 max_size_ 设为私有,因此您需要创建一个 getter 和 setter 以在该类之外访问它。 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_++然后在您的 Stack 类中,您可以获得 max_size_ 值并将其保存在局部变量中,然后将其设置为 1 + 它的当前值以实现 max_size_++

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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