初始化引用成员:不同语法的原因

Initializing a reference member: reason for different syntax

我有两个类,其中一个有另一个的对象作为参考成员:

class myClass{
public:
    myClass() { };
};

class mySecondClass {
public:
    mySecondClass(myClass& reference)
    {
        myClassReference = reference; //doesn't get accepted by the compiler
    };

    myClass& myObjectReference;
};

我发现了(感谢 Passing by reference to a constructor ), mySecondClass(myClass& reference) : myObjectReference(reference){}; 完成了工作。

但是为什么我不能使用myObjectReference = reference;

在构造函数中

mySecondClass(myClass& reference)
{
    myClassReference = reference; //doesn't get accepted by the compiler
};

使用了引用 myClassReference,在创建时应对其进行初始化。但是变量没有初始化。使用了复制赋值运算符。

在这个构造函数中

mySecondClass(myClass& reference) : myObjectReference(reference){}
                                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 

在内存初始化器列表中创建并初始化引用。

为了更清楚地考虑以下演示程序。

#include <iostream>

struct Int
{
    Int() { std::cout << "Int()\n"; }
    Int( int x ) : x( x ) { std::cout << "Int( " << x << " )\n"; }
    Int & operator =( int x )
    {
        std::cout << "Int & operator =( " << x << " )\n";
        this->x = x;

        return *this;
    }

    int x;
};

struct A
{
    A( int x )
    {
        this->value = x;
    }
    Int value;
};

struct B
{
    B( int x ) : value( x ) {}
    Int value;
};

int main() 
{
    A a( 10 );

    std::cout << '\n';

    B b( 10 );

    return 0;
}

它的输出是

Int()
Int & operator =( 10 )

Int( 10 )

也就是说,当构造函数 A 的主体获得控制权时,数据成员已经使用 class Int 的默认构造函数创建。在构造函数的主体中使用了赋值运算符。

与classA的构造函数相反,classB的构造函数使用classInt的构造函数在mem-inkitializer列表中创建了数据成员,其中a参数.

所以现在假设您在 class A 中使用一个引用。那么 "default-initialized" 它实际上并没有被它 shell 指向的任何有效对象初始化参考。因此,在构造函数的主体中,您试图将一个值分配给无处引用的无效引用。所以编译器会报错。

因为{ myClassReference = reference; }被认为是 分配给应该已经初始化的东西。

成员初始化列表: member1{value1}, member2{value2}... 旨在提供初始值(什么都不应该 之前有效)。

参考具体情况,与

情况相同
int i=4;
int &r=i; // the reference is initialised (alias for i)
r=5;      // the reference itself is not changed but
          //   the referenced object (i) is assigned