Re: [cpp] my problem(关于函数的默认参数和变量的生存周期)
ScottField Koo
thuchilde at gmail.com
Sun Mar 2 13:48:03 CST 2008
函数的默认参数需要在编译时就知道值 (我认为)
而你这个,连具体的对象类型都还没定,又怎么能确定它的默认值呢?
这个问题,其实我也折腾过,不过没结果。
你这个程序也应该是google出来的吧,我早就看到过了 8230; 8230;
在08-3-2,marryme <beyond0924 at gmail.com> 写道:
>
> #include <iostream>
> #include <string>
> #include <iterator>
> #include <list>
> #include <algorithm>
> using namespace std;
> template<typename T, typename ForwardIterator=T::iterator>//模板的默认参数
> struct print
> {
>
> void operator() (T& coll, ForwardIterator it=coll.begin() )//函数的默认参数
> {
>
> copy( coll.begin(),coll.end
> (),ostream_iterator<T::value_type>(cout,"\n"));
>
> }
> };
> //现在我已经有了一个list<int> a;
> print(a);//编译不能通过,提示begin()找不道所属的class sturct
> print(a,a.begin());//编译通过
> 主要的是我希望函数总的第二个参数有第一个参数决定,下面是个简单的例子:
> int test(int a, int b=a)
> {
> return b;
> }
> 函数的第二个变量b由第一个变量a决定,但是在vs2005环境下不能编译通过,想问问你有没有什么办法解决又或者有现成的语法实现之。
>
>
> 下面是第二个问题:就比较简单了
> c++ primer 中明确指出,不要返回指向临时
> 对象的指针。但是看下面一段代码:
> int* point(int a=0)
> {
> int* p=new int(a);//这是一个临时变量
> cout<<"in fuction"<<endl<<p<<" "<<*p<<endl;
> return p;
> }
> int main()
> {
> int* p=point();
> cout<<p<<" "<<*p<<endl;
> return 0;
> }
> 执行之后主函数难正确的输出结果0,这就说明
> 在函数中如果一个临时变量本身是通过指针产生的
> 就可以继续存在。
> 然后下面的代码:
> 当返回指向临时变量的指针,但变量不是通过指针生成的,就会出现不可预计的错误。如以下代码:
> #include <iostream>
> using std::cout;
> using std::endl;
> int* point(int a=0)
> {
> cout<<"in fuction"<<endl<<&a<<" "<<a<<endl;
> return &a;
> }
> int main()
> {
> int* p=point();
> cout<<p<<" "<<*p<<endl;
> return 0;
> }返回的结果不可预计
> 所以我想知道在函数中通过new操作符产生的变量生存周期难道是整个程序?
>
> _______________________________________________
> Cpp mailing list
> Cpp at codingnow.com
> http://codingnow.com/mailman/listinfo/cpp
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://codingnow.com/pipermail/cpp/attachments/20080302/05ca56b9/attachment.html
More information about the Cpp
mailing list