2

基本上我想要一个常量——而不是const引用——
引用类中的变量。

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

如果我设置了x = 3I want ato be 3too
所以我希望 a 成为对 x 的引用,使用类似的指针会很容易,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 回答
0

这里的问题实际上是您试图在类型的定义中分配一个引用。那是行不通的,因为根据放置对象的位置,a并且x会有不同的位置。Foo

您需要在Foo创建对象后执行此操作,这意味着在构造函数中

Foo() : a(x), b(y), c(z) {}

请注意,在构造之后尝试初始化引用也是无效的 - 它必须在构造函数中完成,仅此而已。

于 2013-06-22T10:42:39.200 回答
0

不能使用默认赋值运算符,因为您有引用成员。它与您如何初始化它们或将它们初始化为什么无关。这是因为引用不能“重新就位”。

如果您发布导致问题的行会很有帮助。你必须有类似的东西foo1=foo2;。您的解决方案是编写自己的赋值运算符。

于 2013-06-22T13:09:31.417 回答