简体   繁体   English

在同一行中声明成员引用变量

[英]Declaring member reference variables in the same line

I wrote these apparently harmless lines inside my code just for naming convenience: 为了方便起见,我在代码中编写了这些显然无害的行:

struct Foo{
    double vec[2];
    double& a=vec[0],b=vec[1];
};

But for some reason the variable "a" works fine and "b" does not ( it returns garbage). 但是由于某种原因,变量“ a”可以正常工作,而变量“ b”则不能工作(它返回垃圾)。 This is strange since it seemed to be a valid way to declare them . 这很奇怪,因为这似乎是声明它们有效方法 I then tested some alternate ways to do it: 然后,我测试了一些替代方法:

#include <iostream>
using namespace std;
struct Foo{
    double vec[2];
    double& a=vec[0],b=vec[1]; //does not work

    double& c=vec[0];
    double& d=vec[1]; //works

    double ev,fv;
    double& e=ev,f=fv; // does not work

    double& g,h; // does not work
    Foo() : g(vec[0]) ,h(vec[1]){};

    void bar(){
        vec[0]=1;
        vec[1]=2;
        ev=1;
        fv=2;
        cout<<"a: "<<a<<endl;
        cout<<"b: "<<b<<endl;    
        cout<<"\nc: "<<c<<endl;
        cout<<"d: "<<d<<endl;
        cout<<"\ne: "<<e<<endl;
        cout<<"f: "<<f<<endl;        
        cout<<"\ng: "<<g<<endl;
        cout<<"h: "<<h<<endl;

        double& i=vec[0], j=vec[1]; //works
        cout<<"\ni: "<<i<<endl;
        cout<<"j: "<<j<<endl;
    }
};

int main(int, char **) {
    Foo X;
    X.bar();

    double vec[2];
    vec[0]=1;
    vec[1]=2;
    double& k=vec[0],l=vec[1];//works
    cout<<"\nk: "<<k<<endl;
    cout<<"l: "<<l<<endl;
}

In summary, the pairs (a,b), (e,f) and (g,h) don't work properly in the same way (ie the second variable returns some garbage). 总之,对(a,b),(e,f)和(g,h)不能以相同的方式正常工作(即第二个变量返回一些垃圾)。 I know this could be easily avoided by writing like (c,d), but this whole behaviour is puzzling, specially because (a,b) fails while (i,j) and (k,l) work, even though the main difference seems to be where the declaration takes place. 我知道可以通过编写(c,d)来避免这种情况,但是整个行为令人费解,特别是因为(a,b)在(i,j)和(k,l)工作时会失败,即使主要区别在于似乎是进行声明的地方。 Why is that so? 为什么会这样?

Note: C++11 standard. 注意:C ++ 11标准。 Using -pedantic -Wall -Wextra in g++ did not throw any warnings 在g ++中使用-pedantic -Wall -Wextra不会引发任何警告

double& a=vec[0],b=vec[1];

is the same as: 是相同的:

double& a=vec[0];
double b=vec[1];

You can use: 您可以使用:

double& a=vec[0], &b=vec[1];

or, preferably: 或者,最好:

double& a=vec[0];
double& b=vec[1];

As for pointers, putting the & before the space or after it, is not changing anything. 至于指针,将&放在空格之前或之后,并没有改变任何内容。

This will work: 这将起作用:

double &a=vec[0],&b=vec[1];

and also this will work: 而且这将工作:

double& a=vec[0], &b=vec[1];

the first & goes only for a the second for b 第一个&仅对b来说a第二个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM