以后可以初始化引用变量吗?

Jak*_*der 3 c++

最佳解释一个例子:

Class banana {
    int &yumminess;
    banana::banana() {
        //load up a memory mapped file, create a view
        //the yumminess value is the first thing in the view so
        yumminess = *((int*)view);
    }
}
Run Code Online (Sandbox Code Playgroud)

但这不起作用:/当我找到"yumminess"引用变量时,我无法知道视图的位置.现在我只是使用一个指针并一直取消引用它,有什么方法可以为我的课程带来一些额外的便利吗?

πάν*_*ῥεῖ 6

简而言之:不,这是故意不可能的.

三思而后行:像未初始化的引用这样的东西真的不存在; 这根本没有意义.
因此,它们需要在构造封闭类时或在静态初始化时设置.

对于这种情况,您需要使用指针.


除了注意

 yumminess = (int*)view;
Run Code Online (Sandbox Code Playgroud)

无论如何都会被错误地铸造(指针).


"现在我只是使用指针并一直取消引用它......"

这也很容易克服编写适当的成员函数来访问引用.

int* yumminess;

// ...

int& yumminessRef() {
    if(!yumminess) { 
        throw some_appropriate_exception("`yumminess` not initialized properly.");
    }
    return *yumminess;
}
Run Code Online (Sandbox Code Playgroud)