java - 这两个 new 的含义分别是什么?
本文介绍了java - 这两个 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;
}
解决方案
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
并不是你想象的那么简单
这篇关于java - 这两个 new 的含义分别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文