不经意间想到了这个问题,存到栈中的是对象的引用,还是对象的克隆体。简单验证下吧。
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++中的对象则不是。这就导致两者在实现栈的方式有所不同。
本文对比了Java和C++中栈类对于对象存储方式的不同,Java栈存储对象引用,C++栈存储对象副本,导致行为差异。通过示例代码验证,Java中修改栈顶对象影响所有栈内对象,而C++不受影响。

被折叠的 条评论
为什么被折叠?



