首页 > 这两个 new 的含义分别是什么?

这两个 new 的含义分别是什么?

1:下面的c++代码和Java代码干的是同一件事。但是就是因为c++代码不能在new之后直接调用方法。我有点心堵。
2:我认为c++的new 返回的是一个指针,之后通过指针操作相应的成员函数。
3:java 的new 返回的是一个对象,所以可以直接调用相应的方法。

谁能帮忙深层次解答下:

java 代码:

public class test {
    public test() {

    }
    public test(int temp) {
        this.a = temp;
    }
    void A() {
        System.out.println(a);
    }

    private int a;

    public static void main(String[] args) {
        new test(1).A();
    }
}

c++代码:

#include<iostream>

class test {
public:
    test() = default;
    test(int b) {
        a = b;
    }
    void A() {
        std::cout << a << std::endl;
    }
private:
    int a;
};


int main(int argc,char *argv[])
{
    test mytest(1).A();
    return 0;
}


你上面的java/c++构造对象的方法是有区别的,还有c++才是返回一个真正的对象,而java是类似于指针的东西,你恰好理解反了,而且c++也有类似于java返回指针的用法:new test(1)这样返回的就是一个指针
~~还有就是 这样不行?
test(1).A();
(new test(1))->A(); // 当然这种不推荐,因为有内存泄漏


你的c++没有用new呀


C++: 说好的new

#include<iostream>

class test {
public:
    test() = default;
    test(int b) {
        a = b;
    }
    void A() {
        std::cout << a << std::endl;
    }
private:
    int a;
};


int main(int argc,char *argv[])
{
    test(1).A(); //没问题
    (*(new test(1))).A(); //内存泄露
    (new test(1))->A(); //上一行的语法糖
    return 0;
}

当然这个编程习惯很不好

而且C++的new不是你想象的那么简单

【热门文章】
【热门文章】