2

基本的に 、クラス内の変数への参照はなく、定数が必要です。const

class Foo
{
public:
    double x, y, z;
    double& a = x;
    double& b = y;
    double& c = z;
}

私もx = 3なりたいaと設定 した場合、 a を x への参照にしたいのですが、ポインターを使用すると簡単 ですが、毎回逆参照したくありません.. 3
double* a = &x;

これをコンパイルすると、次のメッセージが表示されます。

warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11 [enabled by default]
warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11 [enabled by default]
warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11 [enabled by default]

しかし、それは主な問題ではありません: 私が今それらを使用しようとすると ( a, b, c) ここのように:

Foo foo;
foo.x = 1.0;
foo.y = 0.5;
foo.z = 5.1;
printf("a: <%f> b: <%f> c: <%f>\n", foo.a, foo.b, foo.c);

次のコンパイラ メッセージが表示されます。

foo.h:5 error: non-static reference member 'double& Foo::a', can't use default assignment operator
foo.h:6 error: non-static reference member 'double& Foo::b', can't use default assignment operator
foo.h:7 error: non-static reference member 'double& Foo::c', can't use default assignment operator

foo.h:5 はdouble& a = x;
foo.h:6 はdouble& b = y;
foo.h:7 ですdouble& c = z;

私の間違いはですか?

4

3 に答える 3

5

代入によって参照を初期化することはできません。次のように、コンストラクターの初期化子リストで初期化する必要があります。

class Foo
{
public:
    double x, y, z;
    double& a;
    double& b;
    double& c;
    Foo() : a(x), b(y), c(z) {}
    // You need an assignment operator and a copy constructor, too
    Foo(const Foo& rhs) : a(x), b(y), c(z), x(rhs.x), y(rhs.y), z(rhs.z) {}
    Foo& operator=(const Foo& rhs) { 
        x=rhs.x;
        y=rhs.y;
        z=rhs.z;
        return *this;
    }
};
于 2013-06-22T10:38:37.403 に答える