C++中的指针和引用与Java中的引用区别

2020-03-08  本文已影响0人  日暮颂歌1991

C++ 代码:

#include <iostream>

using namespace std;

class Test {

public:
    Test(int num) {
        this->num = num;
    }

public:
    int num;
};

void change1(Test & t) {
    t.num = 2;
    // t = new Test(3); // 报错: 引用再次赋值
}

void change2(Test *t) {
    t->num = 2;
    t = new Test(3);    // 指针再次赋值,指向新内存 
}

int main(int argc, char const *argv[])
{
    Test t = Test(1);

    cout << "------引用---------" << endl;
    cout << t.num << endl;
    change1(t);
    cout << t.num << endl;
    

    Test *t2 = new Test(1);
    cout << "------指针---------" << endl;
    cout << t2->num << endl;
    change2(t2);
    cout << t2->num << endl;

    return 0;
}

输出:
------引用---------
1
2
------指针---------
1
2

Java 代码:


class Test {
    public int num;

    Test (int num) {
        this.num = num;
    }
}

public class Learn {
    public static void change(Test t)
    {
        t.num = 2;
        
        t = new Test(3); // 引用 t 再次指向新对象,更像是 C++ 中的指针
    }

    public static void main(String[] args) {
        Test t = new Test(1);
        System.out.println(t.num);
        change(t);
        System.out.println(t.num);
    }
}

输出:
1
2
上一篇下一篇

猜你喜欢

热点阅读