How can I correctly return a vector with class A elements?
In the underlying example: How can I avoid that the method get_Children will complain that the return type is not correct?
Or in compiler language:
test.cpp: In member function std::vector<A, std::allocator<A> > B::getVector() const
:
test.cpp:38: error: passing const Box<A>
as this
argument of std::vector<T,std::allocator<_CharT> > Box<T>::get_Children() [with T = A]
discards qualifiers
#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;
}
Declare Box<T>::get_Children()
as const
. Because B::getVector()
is const, it cannot access a non-const function on a member of B
.
精彩评论