不经意间想到了这个问题,存到栈中的是对象的引用,还是对象的克隆体。简单验证下吧。
1 java中的stack类和C++中的stack类的区别
1.1 java中的stack类
class Test
{
public int val;
public Test(int i)
{
val = i;
}
}
public class StackTest {
public static void main(String[] args)
{
Stack<Test> stack = new Stack<Test>();
Test test = new Test(100);
stack.push(test);
test.val = 0;
test = stack.pop();
System.out.println(test.val);
}
}
输出结果:0。
1.2 C++中的stack类
#include <stack>
class Test
{
public:
int val;
Test(int i)
{
val = i;
}
};
int main()
{
stack<Test> s;
Test test(100);
s.push(test);
test.val = 0;
cout << s.top().val << endl;
system("pause");
return 0;
}
输出结果:100。
1.3 分析
由于java中的对象是引用类型的,而C++中的对象则不是。这就导致两者在实现栈的方式有所不同。