[英]Correctly Call a Method From Newly Created Object Pointer
I am a Java programmer who is taking a C++ class. 我是一名Java程序员,正在学习C ++类。 I can successfully create my object on the stack by not using the "new" keyword.
通过不使用“ new”关键字,我可以在堆栈上成功创建对象。
SeatSelection premium(1,5);
premium.toString();
That code runs my toString() method correctly. 该代码正确运行了我的toString()方法。
I am also attempting to create a new C++ object using the "new" keyword and then attempting to run the toString() method. 我还尝试使用“ new”关键字创建一个新的C ++对象,然后尝试运行toString()方法。
SeatSelection *premium = new SeatSelection(1,5);
I don't know the proper syntax for calling my toString() method. 我不知道调用toString()方法的正确语法。
What I have tried 我尝试过的
premium.toString(); //doesn't compile, premium is of non-class type "SeatSelection*"
What is the syntax for calling a method using a object pointer? 使用对象指针调用方法的语法是什么?
Use operator ->
Along with .
使用运算符
->
和.
(dot) it is so-called class member access operator. (点)它是所谓的类成员访问运算符。
For example 例如
SeatSelection *premium = new SeatSelection(1,5);
premium->toString();
Or you can write 或者你可以写
SeatSelection *premium = new SeatSelection(1,5);
( *premium ).toString();
According to the C++ Standard 根据C ++标准
expression E1->E2 is converted to the equivalent form (*(E1)).E2;
表达式E1-> E2转换为等效形式(*(E1))。E2;
In C++ anytime you use new
you are creating an object on the heap and getting a pointer to that object in return. 在C ++中,只要您使用
new
,就可以在堆上创建一个对象,并获得指向该对象的指针作为回报。
In C++ there are two ways to deference a pointer. 在C ++中,有两种引用指针的方法。
1) Use an asterisk as in (*premium)
, then use a dot operator to call a function on that class (ie (*premium).toString();
). 1)使用
(*premium)
的星号,然后使用点运算符调用该类上的函数(即(*premium).toString();
)。
2) Use the arrow ->
operator as suggested in other examples, which merges the functionality of the asterisk and dot in one fell swoop and "looks prettier" (ie premium->toString();
). 2)使用其他示例中建议的箭头
->
运算符,将星号和圆点的功能合并为一个,并“看起来更漂亮”(即premium->toString();
)。
DON'T FORGET C++
is NOT garbage collected like Java
, so when you new
up a class, you must have a matching delete
, or you will be hemorrhaging memory. 勿忘
C++
不会像Java
那样被垃圾收集,因此,当您new
一个类时,必须具有一个匹配的delete
,否则会浪费内存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.