返回信息流比如我现在有一个Person类
class Person
{
string name;
int age;
}
我现在想把它放到一个容器内,我该怎么定义?
我只知道对于一个整数类型的数组,比如int a[10];可以vector<int>veclist(a,a+10)来定义,那么上面的类该怎么办?
这是一条镜像帖。来源:北邮人论坛 / cpp / #25971同步于 2009/7/8
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖
请教:在c++中怎样用顺序容器定义一个类
Parid
2009/7/8镜像同步12 回复
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
定义一个构造函数,参数写括号里就行
【 在 Parid (Parid) 的大作中提到: 】
: 那再问一下,如果我想向Person里面的变量赋值怎么办?
: 比如我想给name赋值为bupt
: age赋值为54.那么这样用上面你写的容器该怎么写呢?
: ...................
我这样写:
#include<iostream>
#include<string>
#include<vector>
using namespace std;
class P
{
public :
P(string n,int a)
{
name=n;
age=a;
}
string name;
int age;
};
main()
{
P e("dsf",23);
int i;
vector<P>a;
cout<<vector[0].name;
system("pause");
return 0;
}
它报错说: cout<<vector[0].name;这一句
missing template arguments before '[' token
是 a[0].name
。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
【 在 Parid (Parid) 的大作中提到: 】
: 我这样写:
: #include<iostream>
: #include<string>
: ...................
#include<iostream>
#include<string>
#include<vector>
using namespace std;
class P
{
public :
P(string n,int a)
{
name=n;
age=a;
}
string name;
int age;
};
main()
{
P e("dsf",23);
int i;
vector<P> a;
a.push_back(e);
cout<<a[0].name;
system("pause");
return 0;
}