您的位置:首页 > 编程语言 > C语言/C++

【C++学习笔记】使用new创建动态结构

2017-04-03 17:21 555 查看
一、创建方法

inflatable * ps = new inflatable;

二、访问成员

1、访问方法1

创建动态结构时,不能将成员运算符句点用于结构名,因为这种结构没有名称,只是知道它的地址。C++专门为这种情况提供了一个运算符:箭头成员运算符(->)

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

2、访问方法2

如果ps是指向结构的指针,则*ps就是被指向的值——结构本身,由于*ps是一个结构,因此(*ps).price是该结构的price成员。C++的运算符优先规则要求使用括号。

三、例子

#include <iostream>
struct inflatable
{
char name[20];
float volume;
double price;
};
int main()
{
using namespace std;
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;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: