11 12
发新话题
打印

借问一下,关于C++中函数返回值的问题

借问一下,关于C++中函数返回值的问题

如果我希望我的函数返回一个vector型值,并把这个值赋给变量a,程序应该怎么写呢?

TOP

vector func()
{
vector r = new vector();
return r;
}

vector a;
a = func();

new是new在heap上,不用想太多了,不会出函数就清空的。

好不容易中计,怎能轻易放弃。

TOP

引用:
原帖由 imac 于 2007-12-18 03:35 PM 发表
vector func()
{
vector r = new vector();
return r;
}

vector a;
a = func();

new是new在heap上,不用想太多了,不会出函数就清空的。
我试过了,code是这样写的:

vector<string> func(){
vector<string> r=new vector<string>();
return r;
}

可是提示错误说:

error: 'initializing' : cannot convert from 'class std::vectorNo constructor could take the source type, or constructor overload resolution was ambiguous

我也不知道这是为什么 [ 本帖最后由 Zerk 于 2007-12-18 03:46 PM 编辑 ]

TOP

是不是应该:
vector* func(){
vector* r=new vector();
return r;
}

or

vector func(){
vector r; // 不用new动态分配
return r;
}

TOP

引用:
原帖由 kknd 于 2007-12-18 04:09 PM 发表
是不是应该:
vector* func(){
vector* r=new vector();
return r;
}

or

vector func(){
vector r; // 不用new动态分配
re ...
Great, it works, but seems the function declaration I got from others is just:

vector<string> func(){};

anyway, thx very much

TOP

vector* func(){
vector* r=new vector();
return r;
}
是动态分配,用完以后应该要delete:
vector* a = func(); // a是指针,指向func里面new的那个vector
...
delete a;

vector func(){
vector r; // 不用new动态分配
return r;
是静态分配,不用delete:
vector a = func(); // a 不是指针,是func里面那个vector的拷贝。func里面那个vector出了func就自动释放了

如果数组很大最好用第一种方法。

TOP

你要用vector< string >就不一样了吧...

non-scalar type...

我刚才写的是vector< int >,但是< >里面的被系统自动忽略了

我也想迷糊了,vector是没有non-parameter cstor的... 动态分配吧 [ 本帖最后由 imac 于 2007-12-18 04:34 PM 编辑 ]

好不容易中计,怎能轻易放弃。

TOP

引用:
原帖由 Zerk 于 2007-12-18 05:13 PM 发表



Great, it works, but seems the function declaration I got from others is just:

vector<string> func(){};

anyway, thx very much
If the declaration is vector<string> func();
then it should be:

vector<string> func(){
vector<string> r;

return r;
}

TOP

引用:
原帖由 Zerk 于 2007-12-18 04:42 PM 发表


我试过了,code是这样写的:

vector<string> func(){
vector<string> r=new vector<string>();
return r;
}

可是提示错误说:

error: 'i ...
if you use new then the return type needs to be vector<string> *

TOP

引用:
原帖由 chao 于 2007-12-18 04:32 PM 发表


If the declaration is vector<string> func();
then it should be:

vector<string> func(){
vector<string> r;

return r;
}
hehe, thanks a lot, actually my question is, could I assign a value to "A" in this way:


vector<string> func(){} //function declaration;
string <string> A; //without initialization;
A=func();//seems this doesn't work.

TOP

 11 12
发新话题