从派生类对象调用基类方法时出错。基类和派生类都是模板化的

时间:2017-01-27 07:23:53

标签: c++ templates inheritance

我正在用模板练习一些C ++继承概念。我写了这个基类:

template <typename type1, typename type2>
class baseClass {
private:
    type1 member1;
    type2 member2;

public:
    baseClass() {};
    baseClass(type1 member1, type2 member2):member1(member1), member2(member2) {};
    type1 get_member1();
    type2 get_member2();
    ~baseClass() {};
};

和派生类:

template <typename type1, typename type2, typename type3>
class derivedClass : public baseClass<type1, type2> {
private:
    type3 member3;
public:
    derivedClass(){};
    derivedClass(type1 member1, type2 member2, type3 member3): baseClass<type1, type2>(member1, member2), member3(member3){};
    type3 get_member3();
};

我正在从主要功能进行这种操作:

int main(int argc, const char * argv[]) {
    derivedClass<int, int, int> object(1, 2, 3);
    cout << object.get_member1() << endl;
    cout << object.get_member1() << " " << object.get_member2() << " " << object.get_member3() << endl;
}

当我尝试编译上述程序时,编译器会出错。我尝试在线搜索此问题,但没有得到任何具体的答案。我是C ++模板的新手,不知道如何处理它们。请帮我搞清楚。谢谢!

编辑:get_member *方法的定义:

template <typename type1, typename type2>
type1 baseClass<type1, type2>::get_member1() {
    return member1;
}

template <typename type1, typename type2>
type2 baseClass<type1, type2>::get_member2() {
    return member2;
}

template <typename type1, typename type2, typename type3>
type3 derivedClass<type1, type2, type3>::get_member3() {
    return member3;
}

1 个答案:

答案 0 :(得分:0)

见这里:corrected-code

#include <iostream>
using namespace std;

template <typename type1, typename type2>
class baseClass {
private:
    type1 member1;
    type2 member2;

public:
    baseClass() {}
    baseClass(type1 member1, type2 member2):member1(member1), member2(member2) {}
    type1 get_member1(){return member1;}
    type2 get_member2(){return member2;}
    virtual ~baseClass() {};
};

template <typename type1, typename type2, typename type3>
class derivedClass : public baseClass<type1, type2> {
private:
    type3 member3;
public:
    derivedClass(){};
    derivedClass(type1 member1, type2 member2, type3 member3):     baseClass<type1, type2>(member1, member2), member3(member3){};
    type3 get_member3() {return member3;}
    ~derivedClass(){}
};


int main(int argc, const char * argv[]) {
    derivedClass<int, int, int> object(1, 2, 3);
    cout << object.get_member1() << endl;
    cout << object.get_member1() << " " << object.get_member2() << " " <<    object.get_member3() << endl;
    return 0;
}