【发布时间】:2019-06-23 22:48:14
【问题描述】:
我想在以下场景中显式更改结构的构造函数中的第二个参数。有没有可能,如果有,怎么做?
struct foo{
int x;
int y;
foo(int a=4, int b=6){
x=a;
y=b;
}
};
int main(){
foo *f = new foo();
cout<<f->x<<" "<<f->y<<endl;
//4 6
foo *g = new foo(3,4);
cout<<g->x<<" "<<g->y<<endl;
//3 4
foo *h = new foo(3);
cout<<h->x<<" "<<h->y<<endl;
//3 6
//Can something like this be
//done in C++, if I want
//to change the value of the
//second variable only
foo *k = new foo(b = 13);
return 0;
}
【问题讨论】:
-
这里绝对没有必要使用
new。foo g(3,4);或foo g{3,4};工作得很好。而且您不会忘记像以前一样致电delete。
标签: c++ constructor