为什么编译器会允许默认情况下使用构造函数使用引用成员初始化Class

问题描述 投票:-1回答:1

我正在学习C ++入门5,并且知道在类定义引用成员时需要构造函数初始化程序,否则编译器会抱怨它。

但是,我编写了一个静态工厂方法以空语句重现该类。

#include <iostream>

using namespace std;

//Learning default initializing values.
class Default {
   public:
    Default(int t) : r(t) {}
    static Default FromDefault() {}

    friend ostream& operator<<(ostream& os, const Default& d) {
        os << "c " << d.c << endl
           << "a " << d.a << endl
           << "b " << d.b << endl
           << "d " << d.d << endl
           << "l " << d.l << endl;
        return os;
    }

   private:
    int& r;  //a reference which require to be initialized
    char c;
    int a;
    float b;
    double d;
    long l;
};

int main() {
    cout << Default::FromDefault();
    return 0;
}

我以为代码不会通过编译器,但确实可以。只要我不使用成员r,就不会发生错误。

似乎引用类成员未能初始化,我只是想知道为什么编译器不会发现此错误!

c++ class reference default
1个回答
3
投票

[FromDefault表现出不确定的行为,通过到达闭合括号而不遇到return语句。


在不相关的注释上,Default(int t)构造函数将引用r绑定到局部变量。构造函数返回后,t被破坏,r悬空。以后再尝试使用它都将显示不确定的行为。

© www.soinside.com 2019 - 2024. All rights reserved.