如何定义一个对象的vector

Hinagi 2009-10-09 10:27:19
我自己写了一个类 只有一个有参数的构造函数.
Cxxx(string, string);

我现在想定义一个这个类的类型的vector应该怎么写啊?


没有参数的话好说,但是我现在的构造函数有参数...定义的时候老报错
...全文
132 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
Hinagi 2009-10-09
  • 打赏
  • 举报
回复
4楼说的是正确的,果然还是基础没学好啊,.....结贴了,分不多,意思一下
谢谢各位
Hinagi 2009-10-09
  • 打赏
  • 举报
回复
5楼的方法我试过,但是我把对象加到里面以后再访问对象里面的数据的时候得出来的是空,不知道为什么

vector<CSoundFile *> vcs;

CSoundFile s(L"1", L"1");
vcs.push_back(&s);
vcs[0]->getFirstString(); //这个函数的实现是直接return构造函数的第一个参数,但是打出来是空


6楼说的我也加上了,还是报上面3楼我贴的一样的错误.


4楼说的还没试,我先试试(主要是还不知道怎么写,呵呵...)
xingzhe2001 2009-10-09
  • 打赏
  • 举报
回复
你需要再另外定义一个没有参数的构造函数

Cxxx(){}
chlaws 2009-10-09
  • 打赏
  • 举报
回复
[code=c/c++]
#include<iostream>
#include<vector>
#include<string>
#include<cstdlib>
using namespace std;

class A{
public:
A(string s1,string s2)
{
cout << "first argument:"<< s1
<< "second argument:"<<s2 << endl;
}
~A(){}
};

int main()
{

vector<A*> veca;
A a("aa","bb");
veca.push_back(&a);

system("PAUSE");
return 0;
}

[/code]
erwin1984 2009-10-09
  • 打赏
  • 举报
回复
需要定义拷贝构造函数和重载等于,因为vector 的一些函数的实现需要复制元素。
而没有写构造函数的的话,编译器会默认实现这些。

Cxxx(const Cxxx &src);
Cxxx &operator = (const Cxxx &src);
Hinagi 2009-10-09
  • 打赏
  • 举报
回复
vector<CSoundFile> vcs; //这样定义不会报错

CSoundFile c1(L"", L"");
vcs.push_back(c1); //但是在往里面加元素的时候就错了


1>C:\Program Files\Microsoft Visual Studio 8\VC\ce\include\vector(1125) : error C2248: 'CSoundFile::CSoundFile' : cannot access private member declared in class 'CSoundFile'
1> e:\audiorecorder\audiorecorder\SoundFile.h(59) : see declaration of 'CSoundFile::CSoundFile'
1> e:\audiorecorder\audiorecorder\SoundFile.h(38) : see declaration of 'CSoundFile'
1> C:\Program Files\Microsoft Visual Studio 8\VC\ce\include\vector(1117) : while compiling class template member function 'void std::vector<_Ty>::_Insert_n(std::_Vector_iterator<_Ty,_Alloc>,unsigned int,const _Ty &)'
1> with
1> [
1> _Ty=CSoundFile,
1> _Alloc=std::allocator<CSoundFile>
1> ]
1> .\MAppWinMain.cpp(195) : see reference to class template instantiation 'std::vector<_Ty>' being compiled
1> with
1> [
1> _Ty=CSoundFile
1> ]
1>CMAppPropertiesDlg.cpp
w0911h 2009-10-09
  • 打赏
  • 举报
回复
vector<Cxxx>不行?
ysuliu 2009-10-09
  • 打赏
  • 举报
回复
能贴上你的代码吗?

64,685

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧