[英]non-static reference member ‘int& Property<int>::value’, can’t use default assignment operator
在某些C ++代码中,我遇到了一个编译时错误,这似乎表明我正在尝试重新建立引用。 但是我非常确定我不会尝试重新引用。 我不了解错误的原因。 也许我很傻,缺少明显的东西。 或者问题可能反映了我没有充分理解的C ++模板编程的深层原理。 无论哪种方式,我希望你们中的一些人都能提供帮助。 这是代码:
// p.cpp - slimmed down demonstration of error in prop.cpp
template<class T>
class Property {
protected:
T& value;
public:
explicit Property(T& a) : value(a) { }
// default "copy" setter
virtual Property<T>& operator=(T a) { value = a; return *this; }
// default "copy" getter
virtual operator T() const { return value; }
template<class U> // must invoke U virtual getter and T virtual setter
Property<T>& operator=(const Property<U>& newval)
{ return (*this = U(newval)); }
/* // uncommenting this eliminates the error
Property<T>& operator=(const Property<T>& newval)
{ return (*this = T(newval)); }
/**/
};
int main()
{
//* // this code produces the error
{
int i_ = 10, j_;
Property<int> i (i_), j (j_);
j = i;
}
/**/
/* // this code does NOT produce the error
{
int i_ = 10;
long j_;
Property<int> i (i_);
Property<long> j (j_);
j = i;
}
/**/
return 0;
}
当我使用命令g++ -op p.cpp
用gcc (Ubuntu/Linaro 4.6.1-9ubuntu3) 4.6.1
编译此g++ -op p.cpp
得到以下输出:
p.cpp: In member function ‘Property<int>& Property<int>::operator=(const Property<int>&)’:
p.cpp:4:7: error: non-static reference member ‘int& Property<int>::value’, can’t use default assignment operator
p.cpp: In function ‘int main()’:
p.cpp:33:13: note: synthesized method ‘Property<int>& Property<int>::operator=(const Property<int>&)’ first required here
在您告诉我我要重新建立参考之前,请记住:
取消注释Property::operator=
的定义,该定义在右侧显式采用与左侧的构造类型相同的构造类型,从而消除了该错误。 因此,问题本质上不是通过*this
访问Property<int>::value
。
独立地,如main()
所示,实例化Property
类模板中的operator=
方法模板,并且当=
右侧的值的数据类型与=
左侧的数据类型不同时,可以正常工作。
value
是一个引用,但至少在一般情况下,用=
为其赋值没有什么错。 它是非const
。 因此,一旦实例化它(通过Property
唯一的构造函数中的初始化列表来保证),则为其分配值不会尝试重新设置它,而是为它所引用的内存位置分配一个新值。
我将提供更大的文件prop.cpp
其中包含了每种的(成功)的单元测试Property
的成员函数, 如果被请求 。
您可能会注意到,此代码是尝试(部分)在C ++中实现“类似于函数”(“ C#样式”)属性。 但是,这个问题不是关于在实际的C ++项目中执行此操作是否真正合适,也不是关于我选择的模式是否最合适的问题。 稍后我可能会提出其他问题。 如果您想评论或批评我的方法,我很感兴趣。 我只要求您不要在这里这样做,因为这会分散您这个问题的特定目的。 相反,您可以发布自己的问题(可能带有自己的答案),并在此处发布简短评论以链接到新问题。
正如编译器所说,不能使用编译器生成的赋值运算符来分配非静态引用。 需要用户定义的副本分配运算符。
用户定义的赋值运算符执行对value
引用的对象的value
,方法是先调用operator T()
以获得类型T
的临时值,然后调用Property<T>& operator=(T a)
来执行value = a
,它将引用的对象替换为从转换运算符获得的值。
如果没有从您的类派生任何东西,则您的operator =等效于
// uncommenting this eliminates the error
Property<T>& operator=(const Property<T>& newval)
{
// return (*this = T(newval)); // convert to T, then assign
value = newval.value; // assign the referenced object
return *this;
}
第二种情况似乎更清楚:使用了用户提供的赋值运算符。
{ U u = U(newval); // extract a value
*this = u; // use the custom assignment operator that takes a
// value as an argument and assigns to a reference
}
第一种情况不同:未选择用户定义的赋值运算符,并且编译器尝试对其进行合成。 对于非静态引用,这是不可能的,因此程序格式错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.