【原创】一起学C++ 之->(箭头符号) ---------C++ primer plus(第6版)


1.C++新手在指定结构成员时,不知道何时用.运算符,何时是用->运算符。

 

 

 

结论:如果结构标识符是结构名,则使用句点运算符;如果标识符是指向结构的指针,则使用箭头运算符。

 

#include <iostream>
struct inflatable
{
    char name[20];
    float volume;
    double price;
};
int main(){
    using namespace std;
    int a;    //仅为保持dos界面 
    inflatable *ps=new    inflatable;
    cout<<"Enter name of inflatable item: ";
    cin.get(ps->name,20    );
    cout<<"Enter volume in cubic feet: ";
    cin>>(*ps).volume;
    cout<<"Enter price : $";
    cin>>ps->price;
    cout<<"Name: "<<(*ps).name<<endl;
    cout<<"Volume: "<<ps->volume<<"cubic feet\n";
    cout<<"Price: $"<<ps->price<<endl;
    delete ps;
    cin>>a;   //仅为保持dos界面
    return 0;
}

输出结果:

对于例子中的 *ps 这个结构指针:

ps->name 等价于 (*ps).name

2.new创建的对象不是用“*”或“.”来访问该对象的成员函数的,而是用运算符“->”

 

    Rec *rec=new Rec(3,4);
      rec->getArea();
      delete rec;

C++用new创建对象时返回的是一个对象指针,用new 动态创建的对象必须用delete来撤销该对象。只有delete对象才会调用其析构函数。

 

注意:new创建的对象不是用“*”或“.”来访问该对象的成员函数的,而是用运算符“->”;

 

总结:指针对象调用的方法都要用 ->


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM