2016-12-14 83 views
2

我给下面的例子来说明我的问题:C++拷贝赋值运算符的参考对象变量

class Abc 
{ 
public: 
    int a; 
    int b; 
    int c; 

}; 

class Def 
{ 
public: 
    const Abc& abc_; 

    Def(const Abc& abc):abc_(abc) { } 

    Def& operator = (const Def& obj) 
    { 
     // this->abc_(obj.abc_); 
     // this->abc_ = obj.abc_; 
    } 
}; 

在这里,我不知道如何定义拷贝赋值运算符。你有什么想法?谢谢。

+7

无法完成。如果你想让'Def'赋值,让它包含一个指针,而不是引用。 – Quentin

+1

^^^案例和观点:['std :: reference_wrapper'](http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper) – StoryTeller

+0

您*可以*使用复制构造函数来实现结果你要。但是你不能完成任务,因为参考成员只能在施工期间设置。 – 0x5453

回答

6

引用不能分配给。你需要的东西可以。一个指针可以工作,但它们是非常可滥用的。

std::reference_wrapper怎么样?

#include <functional> 

class Abc 
{ 
public: 
    int a; 
    int b; 
    int c; 
}; 

class Def 
{ 
public: 
    std::reference_wrapper<const Abc> abc_; 

    Def(const Abc& abc):abc_(abc) { } 

    // rule of zero now supplies copy/moves for us 

    // use the reference 
    Abc const& get_abc() const { 
     return abc_.get(); 
    } 
}; 
3

无法分配参考。由于这个原因,人们只能通过放置新的和复制结构来定义它:

Def& operator = (const Def& obj) 
{ 
     this->~Def(); // destroy 
     new (this) Def(obj); // copy construct in place 
} 

但它确实是不需要的。只需使用一个指针。

+0

'Abc'看起来是可分配的。 OP不能分配,而不是使用新的布局? – StoryTeller

+0

* Yuck *。这既聪明又可怕。 +1。 – Quentin

+2

@StoryTeller这将修改当前的'Abc',而不是“重新绑定”的参考。 – Quentin