2013-02-22 62 views
0

下面的代码是正确的混乱关于C++类参考

string s1="abc"; 
    string s2="bcd"; 
    string &rs1=s1; 
    string &rs2=s2; 
    rs1=rs2; 
    cout<<rs1<<"----"<<rs2<<endl; 

与以下几部件代码将编译错误:

class A 
{ 
public: 
    A(string& a):ma(a) { } 

    string& ma; 
}; 

string s1="abc"; 
string s2="bcd"; 
A oa(s1); 
A ob(s2); 
oa=ob; 
cout<<oa.ma<<"----"<<ob.ma<<endl; 

以上数据string&类型分配,为什么把它们放到类会引起编译错误? (gcc版本4.7.1)

错误信息是

non-static reference member 'std::string& A::ma', can't use default assignment operator 
+2

我相信这是因为字符串传递到ctor(string a)的值,这是一个不允许初始化字符串ref的临时对象? – 2013-02-22 10:35:12

+0

我改变了,但它仍然有错误 – zhenyuyang 2013-02-22 10:48:04

+0

@zhenyuyang请将错误的*确切*文本作为您的问题的补充发布; **不**在这里的评论。 – WhozCraig 2013-02-22 10:48:56

回答

1

你设定一个成员引用本地临时变量。在你的构造函数中的参数是一个temp)。这导致了“悬挂参考”,这是不好的。

将param更改为引用,或将您的成员更改为非引用。为了您的目的,你可能会想:

class A 
{ 
public: 
    A(string& a):ma(a) { } 

    A& operator =(const A& other) 
    { 
     ma = other.ma; 
     return *this; 
    } 

    string& ma; 
}; 

但是你应该知道,你的类的默认复制构造函数可能不会做你认为它会。

UPDATE

处理为什么上课的时候有一个参考成员的默认拷贝赋值运算符将被删除标准的具体领域:

C++11 § 12.8,p23

A defaulted copy/move assignment operator for class X is defined as deleted if X has: - a variant member with a non-trivial corresponding assignment operator and X is a union-like class, or

  • a non-static data member of const non-class type (or array thereof), or
  • a non-static data member of reference type, or
  • a non-static data member of class type M (or array thereof) that cannot be copied/moved because overload resolution (13.3), as applied to M’s corresponding assignment operator, results in an ambiguity or a function that is deleted or inaccessible from the defaulted assignment operator, or
  • a direct or virtual base class B that cannot be copied/moved because overload resolution (13.3), as applied to B’s corresponding assignment operator, results in an ambiguity or a function that is deleted or inaccessible from the defaulted assignment operator, or
  • for the move assignment operator, a non-static data member or direct base class with a type that does not have a move assignment operator and is not trivially copyable, or any direct or indirect virtual base class.
+0

我改变了这个,但它仍然有错误 – zhenyuyang 2013-02-22 10:46:36

+0

@zhenyuyang我更新它包含了赋值覆盖,但正如我所说的,你可能不喜欢结果。 (顺便说一下'bcd ---- bcd') – WhozCraig 2013-02-22 10:54:17

+0

谢谢!但是为什么当类包含**引用**时不会生成默认赋值运算符? – zhenyuyang 2013-02-22 10:57:31