bri*_*ore 2 c++ const reference
基本上我想要一个常量 - 而不是const引用 -
引用类中的变量.
class Foo
{
public:
double x, y, z;
double& a = x;
double& b = y;
double& c = z;
}
Run Code Online (Sandbox Code Playgroud)
如果我把x = 3我想a是3太
让我想成为为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]
Run Code Online (Sandbox Code Playgroud)
但这不是主要问题:如果我现在尝试使用它们(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);
Run Code Online (Sandbox Code Playgroud)
我得到这个编译器消息:
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
Run Code Online (Sandbox Code Playgroud)
foo.h:5是double& a = x;
foo.h:6是double& b = y;
foo.h:7是double& c = z;
那么什么是我的错?
您无法通过分配初始化引用.它们需要在构造函数的初始化列表中初始化,如下所示:
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;
}
};
Run Code Online (Sandbox Code Playgroud)