Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何正确返回包含a类元素的向量?_C++_Templates - Fatal编程技术网

C++ 如何正确返回包含a类元素的向量?

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 {

在下面的示例中:如何避免方法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
{
    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
成员上的非常量函数