Как я могу правильно вернуть вектор с элементами класса A? - PullRequest
0 голосов
/ 26 июля 2011

В базовом примере: как можно избежать того, чтобы метод get_Children жаловался на неправильный тип возвращаемого значения?

Или на языке компилятора:

test.cpp: в функции-членеstd::vector<A, std::allocator<A> > B::getVector() const: test.cpp: 38: ошибка: передача const Box<A> как this аргумент std::vector<T,std::allocator<_CharT> > Box<T>::get_Children() [with T = A] отбрасывает квалификаторы

#include <vector>
using namespace std;

template <class T> class Box
{
    private:
        std::vector<T> m_data;

    public:
        Box() {};
        virtual ~Box() {}

        void Add(T const &d);
        void Remove();

        T get_Child(size_t i) const;
        size_t get_ChildCount() const;
        std::string get_ChildNames() const;
        std::vector<T> get_Children() { return m_data; }
};

class A
{
    public:
        A();
        ~A();
};

class B
{
    private:
        Box<A> m_Container;
        B(const B &orig);

    public:
        B();
        ~B();
        std::vector<A> getVector() const { return m_Container.get_Children();}
};

int main()
{
    B b;
    std::vector<A> a_vector;

    a_vector = b.getVector();

    return 0;
}

1 Ответ

4 голосов
/ 26 июля 2011

Объявите Box<T>::get_Children() как const. Поскольку B::getVector() является константой, он не может получить доступ к неконстантной функции для члена B.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...