C++ 如何正确返回包含a类元素的向量?
在下面的示例中:如何避免方法get_Children抱怨返回类型不正确 或使用编译器语言: test.cpp:在成员函数中C++ 如何正确返回包含a类元素的向量?,c++,templates,C++,Templates,在下面的示例中:如何避免方法get_Children抱怨返回类型不正确 或使用编译器语言: test.cpp:在成员函数中std::vector B::getVector()const: test.cpp:38:错误:将const-Box传递为std::vector-Box::get_Children()[带T=A]丢弃限定符 #include <vector> using namespace std; template <class T> class Box {
std::vector B::getVector()const
:
test.cpp:38:错误:将const-Box
传递为std::vector-Box::get_Children()[带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;
}
#包括
使用名称空间std;
模板类框
{
私人:
std::向量m_数据;
公众:
Box(){};
虚拟~Box(){}
无效添加(T const&d);
无效删除();
得不到孩子(尺寸)常数;
size\u t get\u ChildCount()常量;
std::string get_ChildNames()常量;
std::vector get_Children(){return m_data;}
};
甲级
{
公众:
A();
~A();
};
B类
{
私人:
盒式集装箱;
B(康斯特B&orig);
公众:
B();
~B();
std::vector getVector()const{return m_Container.get_Children();}
};
int main()
{
B B;
std::向量a_向量;
a_vector=b.getVector();
返回0;
}
声明框::获取子项()
作为常量
。由于B::getVector()
是常量,因此它无法访问B
的成员上的非常量函数,将Box::get_Children()
声明为常量。由于B::getVector()
是常量,因此它无法访问B
成员上的非常量函数