马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
就是我写的一个栈的副本构造器和=重载中
Stack &operator= (Stack &rhs)
{
if(this != &rhs)
{
this->data = new int[size];
unsigned temsp = rhs.sp; //保存rhs的栈指针sp
while(rhs.sp > 0)
{
data[rhs.sp] = 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[size];
}
Stack(Stack &rhs)
{
*this = rhs;
}
Stack &operator= (Stack &rhs)
{
if(this != &rhs)
{
this->data = new int[size];
unsigned temsp = rhs.sp; //保存rhs的栈指针sp
while(rhs.sp > 0)
{
data[rhs.sp] = rhs.pop();
}
this->sp = temsp;
this->size = rhs.size;
rhs.sp = temsp;
}
else
{
std::cout << "相同的两个类\n";
}
return *this;
}
void push(int value)
{
data[sp++] = 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();
}
在类里面当然可以使用,即使是你将其属性改为private也可以被直接调用
|