C++的指针,引用,指向指针的引用和Java中的引用
#include <iostream>
#include<algorithm>
using namespace std;
class Test {
public:
Test(int num) {
this->num = num;
}
public:
int num;
};
//引用
void change0(Test& t) {
t.num = 2;
Test temp(3);
t=temp;
Test test(4);
t=test;
// t = new Test(3); // 报错
}
//指向指针的引用
void change1(Test* & t) {
t->num = 2;
t = new Test(3);
}
//指针
void change2(Test *t) {
Test *a=t;
cout<<t<<" "<<&t<<" "<<(*t).num<<endl;//t表示指针里存的值即指向的对象的地址,&t表示指针自身的地址,*t表示指向的对象的值
t->num = 2;
t = new Test(3); // 指针再次赋值,指向新内存
}
int main(int argc, char const *argv[])
{
Test t3(1);
cout << "------引用---------" << endl;
cout << t3.num << endl;
change0(t3);
cout << t3.num << endl;
Test *t2 = new Test(1);
cout << "------指针---------" << endl;
cout << t2->num << endl;
change2(t2);
cout << t2->num << endl;
Test *t = new Test(1);
cout << "------指针的引用---------" << endl;
cout << t->num << endl;
change1(t);
cout << t->num << endl;
system("pause");
return 0;
}
Either Excellent or Rusty