【问题标题】:How to write the definition of a derived class in c++? [closed]如何在 C++ 中编写派生类的定义? [关闭]
【发布时间】:2019-12-22 08:20:01
【问题描述】:

我不知道用模板编写类函数定义的语法。

我得到一个错误,编译器预期; ,所以是 无效加; 任何人都知道要解决这个问题!

template<class Type 
class basic{
 protected:
    Type x;
 public:
    int value;
    //virtual void  print() =0; 
  basic(Type xArg):x(xArg){}
}; 

template<class Type>
class plus:public basic<Type>{
 public: 
  Type y;
  plus(Type xArg, Type yArg):basic<Type>(xArg),y(yArg){}
  void print(); 

};

//template<class Type> 
void plus<Type>::print(){ 
  cout << "x : " << x << endl;
  cout << "y : " << y << endl;

}

【问题讨论】:

  • 如果取消注释//template&lt;class Type&gt; 行会发生什么?
  • 在此感谢您:)
  • 问题依旧,解决不了
  • 你提到的错误对我来说似乎不存在:godbolt.org/z/T8K08a
  • template&lt;class Type 你只是忘了结束&gt;

标签: c++ templates inheritance virtual


【解决方案1】:

假设我们有一个基类:

template<class T> 
class MyBase {
   public:
    T value;

    virtual void print() {
        std::cout << "MyBase.value: " << value;
    }        
    virtual ~MyBase() = default; 
};

我们可以派生它并像这样覆盖print。它不一定是模板,但我在示例中使用了一个。

template<class T>
class MyDerived : MyBase<T>
{
   public:
    void print() override {
        std::cout << "MyDerived.value: " << MyBase<T>::value;
    }
};

另外,我喜欢用base来表示基类:

template<class T>
class MyDerived : MyBase<T>
{
   public:
    using base = MyBase<T>; // Use this to indicate the base
    void print() override {
        std::cout << "MyDerived.value: " << base::value << '\n';
    }
};

【讨论】:

  • 没问题!希望对您有所帮助!
猜你喜欢
  • 2018-05-09
  • 2019-04-07
  • 1970-01-01
  • 1970-01-01
  • 2021-12-23
  • 1970-01-01
  • 1970-01-01
  • 2018-07-11
  • 1970-01-01
相关资源
最近更新 更多