如何在子类中触发父模板化类的复制构造函数

How can I trigger copy constructor of a parent templated class inside the child class

提问人:afp_2008 提问时间:6/6/2022 更新时间:6/6/2022 访问量:52

问:

如何在子类的复制构造函数中调用父模板化类的复制构造函数?

// Type your code here, or load an example.
#include<vector>
#include <iostream>

template <typename T>
class Parent {
public:
    Parent() {};
    const std::vector<T>& getDims() const { return m_dims; };
    void setDims(const std::vector<T> dims) { m_dims = dims; };
    Parent(const Parent& p) { m_dims = p.getDims(); };
private:
    std::vector<T> m_dims;
};

template <typename T>
class Child : public Parent<T> {
public:
    Child() {};
    const std::vector<T>& getCenter() const { return m_center; };
    void setCenter(const std::vector<T> center) { m_center = center; };
    Child(const Child& c) {
        m_center = c.getCenter();
        // How can I trigger the copy constructor of the parent class
        // and copy m_dims instead of the following
        this->setDims(c.getDims());
    }
private:
    std::vector<T> m_center;
};

int main(){
    Child<int> child1;
    child1.setDims({3, 1, 1, 1}); // Parent function
    child1.setCenter({1, 2, 3, 4}); // Child function

    Child<int> child2 = child1;
    return 0;
}
C++ 模板 复制构造函数

评论


答:

3赞 Nimrod 6/6/2022 #1
template <typename T>
class Child : public Parent<T> {
public:
    Child() {};
    Child(const Child& c): Parent<T>(c) {
        m_center = c.getCenter();
    }
private:
    std::vector<T> m_center;
};

您的基类在这里。Parent<T>