avatar
C++ 什么时候用 "new" ?# Programming - 葵花宝典
s*1
1
如果我有一个 class MyClass, 有一个constructor MyClass(int x).
在main 里面:
1) MyClass myObj(12);
2) MyClass myObj = new MyClass(12);
有什么区别? 哪一个更好?
avatar
d*u
2
用new的话可以不要变量名,直接用指针访问
比如
MyClass *Prt;
Prt = new MyClass(12);
否则好像没啥区别

【在 s***1 的大作中提到】
: 如果我有一个 class MyClass, 有一个constructor MyClass(int x).
: 在main 里面:
: 1) MyClass myObj(12);
: 2) MyClass myObj = new MyClass(12);
: 有什么区别? 哪一个更好?

avatar
t*t
3
下次换个好点的坑来挖, 第二个编译不过去的

【在 s***1 的大作中提到】
: 如果我有一个 class MyClass, 有一个constructor MyClass(int x).
: 在main 里面:
: 1) MyClass myObj(12);
: 2) MyClass myObj = new MyClass(12);
: 有什么区别? 哪一个更好?

avatar
s*1
4
Yea, I meant to say MyClass *myObj = new MyClass(12);
I realized the difference, stack VS heap.
If I declare:
MyClass *myObj = new MyClass(12);
I can access a member function by: myObj->myFunction().
But if I declare
MyClass myObj (12);
What is the syntax for accessing the member function? Is it still myObj->
MyFunction() ?
avatar
d*u
5
myObj->myFunction()实际上是*(myObj).myFunction()的缩写
如果你定义了myClass类型的变量,不能用->访问成员
只能用 myObj.myFunction()

【在 s***1 的大作中提到】
: Yea, I meant to say MyClass *myObj = new MyClass(12);
: I realized the difference, stack VS heap.
: If I declare:
: MyClass *myObj = new MyClass(12);
: I can access a member function by: myObj->myFunction().
: But if I declare
: MyClass myObj (12);
: What is the syntax for accessing the member function? Is it still myObj->
: MyFunction() ?

avatar
s*1
6
ok. so in this case, myObj is a reference variable, not a pointer?

【在 d*****u 的大作中提到】
: myObj->myFunction()实际上是*(myObj).myFunction()的缩写
: 如果你定义了myClass类型的变量,不能用->访问成员
: 只能用 myObj.myFunction()

avatar
f*Q
7
俺跳了,跳楼了。

【在 s***1 的大作中提到】
: Yea, I meant to say MyClass *myObj = new MyClass(12);
: I realized the difference, stack VS heap.
: If I declare:
: MyClass *myObj = new MyClass(12);
: I can access a member function by: myObj->myFunction().
: But if I declare
: MyClass myObj (12);
: What is the syntax for accessing the member function? Is it still myObj->
: MyFunction() ?

avatar
h*i
8
谁都有当新人的时候

【在 f*****Q 的大作中提到】
: 俺跳了,跳楼了。
avatar
k*a
9
怎么都觉得你像是在说java

【在 s***1 的大作中提到】
: ok. so in this case, myObj is a reference variable, not a pointer?
avatar
f*Q
10
她不是新人,她系专门挖坑的。

【在 h***i 的大作中提到】
: 谁都有当新人的时候
avatar
c*0
11
Personally, I think:
The biggest difference is stack vs. heap. #1 allocates the object in stack
while #2 allocates the object in heap, via "new"...
...by doing so, you unleash the devil of dynamic memory allocation in C++
which has many interesting topics covering different stories of memory/
resource (de)allocation, e.g. new operator vs. operator new, smart pointers,
etc.

【在 s***1 的大作中提到】
: 如果我有一个 class MyClass, 有一个constructor MyClass(int x).
: 在main 里面:
: 1) MyClass myObj(12);
: 2) MyClass myObj = new MyClass(12);
: 有什么区别? 哪一个更好?

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。