C ++私有变量作用域规则

时间:2017-10-16 03:15:05

标签: c++ scoping

这是界面

template <class Type>
class stackADT
{
public:
    virtual void initializeStack() = 0;
    virtual bool isEmptyStack() const = 0;
    virtual bool isFullStack() const = 0;
    virtual void push(const Type& newItem) = 0;
    virtual Type top() const = 0;
    virtual void pop() = 0;
    virtual void reverseStack(stackType<Type>& otherStack) = 0;
private:
    int maxStackSize;
    int stackTop;
    Type *list;
};

这是反向堆栈方法,它是类stackType的一部分,它扩展了stackADT

template <class Type>
class stackType : public stackADT<Type>
{
private:
    int maxStackSize;
    int stackTop;
    Type *list;
public:
/***
 Other methods ...

**/
void reverseStack(stackType<Type>& otherStack)
{

    int count = 0;
    otherStack.list = new Type[maxStackSize]; // why does this WORK!!! its private
    otherStack.stackTop = 0; // why does this WORK!!! its private

    //copy otherStack into this stack. 
    for (int j = stackTop - 1; j >= 0; j--)
    {
        otherStack.push(list[j]);
        count++;
    }
}

以下是调用的主循环。

stackType<int> stack1(50);
stackType<int> stack2(50);

stack1.initializeStack();
stack1.push(1);
stack1.push(2);
stack1.push(3);
stack1.push(4);
stack1.push(5);
stack1.reverseStack(stack2);

因此,在Java,PHP,Python(错位命名)和其他OOD中用C ++导致的这种情况不会允许这样做。

2 个答案:

答案 0 :(得分:1)

我猜你很困惑私人实际上做了什么,因为这也适用于Java。

私有意味着其他类的实例(或没有类,意味着函数)不能更改/调用/调用/ ...该成员/方法。这里的重要部分是它说其他类。同一个类的实例可以更改/调用/调用/ ...私有成员/方法。

答案 1 :(得分:0)

如图所示,它无法编译。

重点是函数reverseStack应该是成员方法,所以它应该从以下开始:
void stackADT::reverseStack(stackType<Type>& otherStack)
作为成员方法,它可以访问private变量。

相关问题