c++primer plus复合类型之指针2

来源:互联网 发布:mp3下载软件推荐 编辑:程序博客网 时间:2024/05/28 18:42

使用new创建动态结构

在运行时创建数组优于在编译时创建数组,对于结构亦如此。可以在程序运行时为结构分配所需要的空间,通过使用new运算符实现。

创建步骤分两步进行:

1:创建动态结构:需要同时使用结构类型和new运算符。例如,创建一个未命名的inflatable类型,将其赋值给指针,

inflatable* pt = new inflatable ;


这种句法和c++内置类型用法相同。

2:访问成员变量:有两种方法访问成员变量,

①创建动态结构时,不能使用成员运算符来访问,因为此时结构没有名称,只是知道它的地址而已。c++为这种情况提供了专门的运算符:箭头运算符(->)。该运算符由连字符和大于号组成,可用于指向结构的指针来访问成员变量,例如,pt->price是被指向结构的price成员

②另一种访问成员变量的方法是,(*pt).price方式,*pt是被指针指向的值--结构的本身,由于*pt是一个结构,因此,(*pt).price是该结构的price成员。

下面是创建动态结构和访问成员变量的示例:

#include <iostream>using namespace std;struct  inflatable{char name[20];float volume;double price;};int main(){inflatable* pt=new inflatable;//创建动态结构cout<<"enter name of inflatable:"<<endl;cin.getline(pt->name,20);cout<<"enter volume of inflatable:"<<endl;cin>>(*pt).volume;cout<<"enter price of inflatable:"<<endl;cin>>(*pt).price;return 0;} 
输出:

enter name of inflatable:

fh

enter volume of inflatable:

1.4

enter price of inflatable:
27.99




0 0
原创粉丝点击