简体   繁体   English

当类成员是引用时,无法生成默认赋值运算符?(在C ++中)

[英]Cannot generate default assignment operator when a class member is a reference?(in C++)

Here is my code: 这是我的代码:

class NO {
  public:
    NO(std::string& name):nameValue(name){};

  private:
    std::string& nameValue;           // this is now a reference

};

int main(){

  int b=10,c=20;
  int& d=b;
  d=c;

  std::string p="alpha", q="beta";

  NO x(p), y(q);
  x=y;

  return 0;

}

I get the error: 我收到错误:

"non-static reference member ‘std::string& NO::nameValue’, can’t use default assignment operator"

Why can't I re-assign the object with a reference member when I can do the same with a built-in type? 当我可以使用内置类型执行相同操作时,为什么不能使用引用成员重新分配对象?

thanks 谢谢

A reference can be initialized, but not assigned to. 引用可以初始化,但不能分配给。 Once the reference is initialized, it will continue to refer to the same object for as long as it exists. 初始化引用后,只要它存在,它将继续引用同一个对象。 If you don't define an assignment operator, the compiler will synthesize one that does member-wise assignment, but in this case that's impossible, so the compiler can't/won't synthesize one at all. 如果你没有定义赋值运算符,编译器将合成一个执行成员分配的运算符,但在这种情况下这是不可能的,因此编译器根本不能/不会合成一个。

You can define an assignment operator yourself. 您可以自己定义赋值运算符。 It's up to you to decide exactly how to deal with a member that's a reference. 您可以自行决定如何处理作为参考的成员。 Most of the time, you just define your object to not contain any references though. 大多数情况下,您只是将对象定义为不包含任何引用。

When you get down to it, the primary use for references is almost certainly as parameters. 当你了解它时,引用的主要用途几乎肯定是参数。 As members of a class, they don't make sense very often, and in the rare case that they do make sense, the objects of that class probably shouldn't support assignment. 作为一个类的成员,它们经常没有意义,并且在极少数情况下它们确实有意义,该类的对象可能不应该支持赋值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM