【问题标题】:How can I store reference of a class in the same type of class in C++?如何将类的引用存储在 C++ 中相同类型的类中?
【发布时间】:2021-11-01 11:40:01
【问题描述】:

我有一个 Person 类,我想在该类中存储另一个 Person 的引用,但我收到错误:无法引用函数“Person::operator=(const Person &)”(隐式声明)——它是一个被删除的函数

在函数getThem()中

class Person {
private:
    Person& them;
    int number;
public:
    Person giveYourself(){
        return *this;
    }
    int giveNumber(){
        return number;
    }
    void getThem(Person& they){
        them = they.giveYourself();
    }
};

【问题讨论】:

  • 您希望them = they.giveYourself(); 行做什么?回想一下,引用不能被反弹。一旦确定了对哪个 Person them 的引用,您以后就不能再决定它应该是对另一个 Person 对象的引用。
  • @NathanPierson 哦,是的,我忘了引用不能被反弹,但是如果我想在这个类中存储另一个相同类类型的对象,我必须为此创建一个指针吗??
  • @NathanPierson 我希望这个类可以存储更多人
  • 一旦引用被初始化为指向一个对象,它就不能被重新初始化(使其指向不同的对象)。对引用的任何操作(例如ref = something)都作用于被引用的对象,并且在引用的整个生命周期内都不会更改引用所指的内容。如果要更改引用所指的内容,则需要使用指针。

标签: c++ class oop reference


【解决方案1】:

我只是在回答这个问题,尽管我认为以你的方式做事并不是一个好主意。我相信你需要的是std::list<Person> 或类似的东西。

让我们进入正题。在类中包含引用是完全可以的。但问题是,自动生成的复制赋值运算符和移动赋值运算符不知道如何处理引用。所以你必须手动定义它:

class Person {
private:
    Person& them;
    int number;
public:
    Person &operator=(const Person &another) {
        number = another.number;
        return *this;
    }

    Person giveYourself(){
        return *this;
    }
    int giveNumber(){
        return number;
    }
    void getThem(Person& they){
        them = they.giveYourself();
    }
};

现在可以编译了。

【讨论】:

    猜你喜欢
    • 2020-08-15
    • 2012-04-28
    • 2011-04-21
    • 2018-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-02
    相关资源
    最近更新 更多