
c++new可以为哪些类型分配内存
我知道可以为int,string这些库中的类型申请空间,但是能直接给自定义的结构体申请空间吗?#include<iostream>#include<string>#inc...
我知道可以为int,string这些库中的类型申请空间,但是能直接给自定义的结构体申请空间吗?
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
struct pizza
{
string name;
double diameter;
double weight;
};
int main()
{
pizza* A=new pizza;
cout<<"Enter the name of your pizza:";
getline(cin,*A.name);
cout<<"Enter the diameter of your pizza:";
cin>>*A.diameter;
cout<<"Enter the weight of your pizza:";
cin>>*A.weight;
cout<<endl<<endl<<"Name: "<<*A.name<<endl<<"Diameter: "<<*A.diameter<<endl<<"Weight: "<<*A.weight<<endl;
return 0;
}
这段代码应该怎样改改?要求不直接声明结构,而是用指针分配空间后直接使用。 展开
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
struct pizza
{
string name;
double diameter;
double weight;
};
int main()
{
pizza* A=new pizza;
cout<<"Enter the name of your pizza:";
getline(cin,*A.name);
cout<<"Enter the diameter of your pizza:";
cin>>*A.diameter;
cout<<"Enter the weight of your pizza:";
cin>>*A.weight;
cout<<endl<<endl<<"Name: "<<*A.name<<endl<<"Diameter: "<<*A.diameter<<endl<<"Weight: "<<*A.weight<<endl;
return 0;
}
这段代码应该怎样改改?要求不直接声明结构,而是用指针分配空间后直接使用。 展开
展开全部
可以的。可以为任何类型分配内存空间,new是运算符,不是系统函数,他的功能是被编译器定义的。
展开全部
任何类型都可以,基础类型、结构体、枚举、联合体、类(包括库和自定义),想怎么申请都可以,呜呜呜
既然是指针 你就不要用(对象点)去指向各个成员变量,那是不对的,我给你改的!
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
struct pizza
{
string name;
double diameter;
double weight;
};
int main()
{
pizza* A=new pizza;
cout<<"Enter the name of your pizza:";
getline(cin,A->name);
cout<<"Enter the diameter of your pizza:";
cin>>A->diameter;
cout<<"Enter the weight of your pizza:";
cin>>A->weight;
cout<<endl<<"Name: "<<A->name<<endl<<"Diameter: "<<A->diameter<<endl<<"Weight: "<<A->weight<<endl;
return 0;
}
既然是指针 你就不要用(对象点)去指向各个成员变量,那是不对的,我给你改的!
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
struct pizza
{
string name;
double diameter;
double weight;
};
int main()
{
pizza* A=new pizza;
cout<<"Enter the name of your pizza:";
getline(cin,A->name);
cout<<"Enter the diameter of your pizza:";
cin>>A->diameter;
cout<<"Enter the weight of your pizza:";
cin>>A->weight;
cout<<endl<<"Name: "<<A->name<<endl<<"Diameter: "<<A->diameter<<endl<<"Weight: "<<A->weight<<endl;
return 0;
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
可以,new 与malloc 区别在于new要调用构造函数,所有结构、类都有构造函数(默认或自定义)
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
可以,NEW是开辟地址空间,能用于所有类型,使用之后记得delete
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
可以给自定义的结构体,自定义的类分配空间。
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询