阿西吧 发表于 2017-7-7 11:28:24

C++ protected的问题

就是我写的一个栈的副本构造器和=重载中
Stack &operator= (Stack &rhs)
        {
                if(this != &rhs)
                {
                        this->data = new int;
                        unsigned temsp = rhs.sp;        //保存rhs的栈指针sp
                        while(rhs.sp > 0)
                        {
                                data = rhs.pop();
                        }
                        this->sp = temsp;
                        this->size = rhs.size;
                        rhs.sp = temsp;
                }
                else
                {
                        std::cout << "相同的两个类\n";
                }
                return *this;
        }

rhs.sp是protected里面的,但是为什么我下断看还可以赋值给rhs.sp呢
不是说protected保护起来的对象不能进行访问吗?

#include<iostream>

class Stack
{
public:
        Stack(unsigned int size = 100)
        {
                this->size = size;
                sp = 0;
                data = new int;
        }

        Stack(Stack &rhs)
        {
                *this = rhs;
        }

        Stack &operator= (Stack &rhs)
        {
                if(this != &rhs)
                {
                        this->data = new int;
                        unsigned temsp = rhs.sp;        //保存rhs的栈指针sp
                        while(rhs.sp > 0)
                        {
                                data = rhs.pop();
                        }
                        this->sp = temsp;
                        this->size = rhs.size;
                        rhs.sp = temsp;
                }
                else
                {
                        std::cout << "相同的两个类\n";
                }
                return *this;
        }

        void push(int value)
        {
                data = value;
        }
       
        int pop()
        {
                return data[--sp];
        }

        ~Stack()
        {
                delete []data;
        }

protected:
        unsigned int size;
        unsigned int sp;
        int *data;
};

void main()
{
        Stack stack1;
        stack1.push(1);
        stack1.push(2);

        Stack stack2 = stack1;
        std::cout << stack2.pop();
}

BngThea 发表于 2017-7-7 16:48:42

在类里面当然可以使用,即使是你将其属性改为private也可以被直接调用

阿西吧 发表于 2017-7-7 17:08:14

BngThea 发表于 2017-7-7 16:48
在类里面当然可以使用,即使是你将其属性改为private也可以被直接调用

谢谢啦,就是一个类里面的方法引用传递同一个类,然后就可以用调用那个类里的保护成员了吗
页: [1]
查看完整版本: C++ protected的问题