Return 通过在 switch 语句中引用
Return by reference inside a switch statement
我想 return 通过引用开关内的变量,例如:
sometype & getbar();
void foo() {
switch ( {statement} ) {
case {statement}:
sometype & handle = getbar();
...
但是我遇到了编译器错误:
initialization of 'identifier' is skipped by 'case' label
initialization of 'identifier' is skipped by 'default' label
而且看起来不可能这样做:
void foo() {
sometype & handle;
switch ( {statement} ) {
case {statement}:
handle = getbar();
...
因为引用变量需要初始化。
有没有办法在保留 switch 语句的情况下做到这一点?
是的,有。将 case 语句的主体括在方括号中,如下所示:
case {statement}:
{
sometype & handle = getbar();
...
}
我想 return 通过引用开关内的变量,例如:
sometype & getbar();
void foo() {
switch ( {statement} ) {
case {statement}:
sometype & handle = getbar();
...
但是我遇到了编译器错误:
initialization of 'identifier' is skipped by 'case' label
initialization of 'identifier' is skipped by 'default' label
而且看起来不可能这样做:
void foo() {
sometype & handle;
switch ( {statement} ) {
case {statement}:
handle = getbar();
...
因为引用变量需要初始化。
有没有办法在保留 switch 语句的情况下做到这一点?
是的,有。将 case 语句的主体括在方括号中,如下所示:
case {statement}:
{
sometype & handle = getbar();
...
}