我有两个类,其中一个类上有另一个作为参考成员的对象:
class myClass{
public:
myClass() { };
};
class mySecondClass {
public:
mySecondClass(myClass& reference)
{
myClassReference = reference; //doesn't get accepted by the compiler
};
myClass& myObjectReference;
};
我发现了(感谢通过引用构造函数传递),则mySecondClass(myClass& reference) : myObjectReference(reference){};
完成该工作。
但是为什么我不能使用myObjectReference = reference;
?
这是因为{ 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
在构造函数中
mySecondClass(myClass& reference)
{
myClassReference = reference; //doesn't get accepted by the compiler
};
使用了在创建时应当初始化的参考CCD_ 5。但是,变量未初始化。使用了复制分配运算符。
在此构造函数中
mySecondClass(myClass& reference) : myObjectReference(reference){}
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
引用是在mem初始值设定项列表中创建和初始化的。
为了使其更加清晰,请考虑以下演示程序。
#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的主体获取控件时,数据成员已经使用类Int的默认构造函数创建。在构造函数的主体中,使用了赋值运算符。
与类A的构造函数相反,类B的构造函数使用带参数的类Int的构造函数在mem-ininitializer列表中创建数据成员。
因此,现在假设您在类a中使用引用。然后它是"默认初始化的",也就是说,它实际上没有被它shell引用的任何有效对象初始化。因此,在构造函数的主体中,您试图将一个值分配给一个不引用任何内容的无效引用。因此编译器会发出一个错误。