基本上我想要一个常量——而不是const
引用——
引用类中的变量。
class Foo
{
public:
double x, y, z;
double& a = x;
double& b = y;
double& c = z;
}
如果我设置了x = 3
I want a
to be 3
too
所以我希望 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;
那么我的错误是什么?