首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何正确地实现容器类中元素的更改?

如何正确地实现容器类中元素的更改?
EN

Stack Overflow用户
提问于 2020-01-19 21:29:10
回答 1查看 43关注 0票数 1

我正在构建一个容器类型,它包含指向类传家宝的指针。我的问题是,我似乎无法使用以下内容来更改元素:

代码语言:javascript
复制
container[0] = x

这里有一个很小的例子,可以重现我的问题。

代码语言:javascript
复制
#include <iostream>
#include <vector>
#include <memory>

using namespace std;


class Animal {

protected:
    std::string noise = "None";
public:
    Animal() = default;

    virtual ~Animal() = default;

    virtual std::string getNoise() {
        return noise;
    }

};

class Duck : public Animal {
public:
    Duck() {
        noise = "Quack!";
    }
};


class Dog : public Animal {
public:
    Dog() {
        noise = "Bark!";
    }
};

class Cat : public Animal {
public:
    Cat() {
        noise = "Me-thefuck-ow!";
    }

    Cat& operator=(Cat const& other) {
        noise = other.noise;
        return *this;
    }
};

typedef std::shared_ptr<Animal> AnimalPtr;


class AnimalsContainer {
public:
    std::vector<AnimalPtr> animals;
    AnimalPtr front;
    Duck duck;
    Dog dog;

    AnimalsContainer() {
        animals.push_back(std::make_unique<Animal>(duck));
        animals.push_back(std::make_unique<Animal>(dog));
        front = animals[0];
    }
    AnimalsContainer(AnimalsContainer& animalsContainer) = default;
    ~AnimalsContainer() = default;
    AnimalsContainer& operator=(const AnimalsContainer&  animalsContainer) = default;
    AnimalsContainer& operator=(AnimalsContainer&& animalsContainer) = default;

    AnimalPtr operator[](int index){
        return animals[index];
    }
};


int main() {
    AnimalsContainer animalsContainer;

    cout << animalsContainer[0]->getNoise() << endl;

    Cat cat;
    animalsContainer[0] = std::make_unique<Animal>(cat);

    cout << animalsContainer[0]->getNoise() << endl;
    return 0;
}

这一产出如下:

代码语言:javascript
复制
Quack!
Quack!

我想要的地方:

代码语言:javascript
复制
Quack!
Meow!
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-01-19 21:41:01

在此:

代码语言:javascript
复制
AnimalPtr operator[](int index) {
    return animals[index];
}

您按值返回,然后为副本分配一个新值。您应该返回一个引用:

代码语言:javascript
复制
AnimalPtr& operator[](int index) {
    return animals[index];
}

而且,您可能打算在所有情况下使用make_shared而不是make_unique

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59814565

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档