陌生缘林 2015-05-02 12:44 采纳率: 0%
浏览 2781

C++,类模板作为基类派生及指针的问题。

      **C++,类模板作为基类派生某几个类,可不可以定义指向基类的指针,然后通过这个指针来指向各个派生类?大家帮忙解答一下。我是初学者,勿喷啊!**            以下面例子为例。C++的。

    #include<iostream>
    using namespace std;
    template<class T1>
    class A
    {
     protected:
            T1 a;
     public:
           virtual void output1();
           virtual void input();
           virtual void output2();
      };

     template<class T1>
     void A<T1>::output1()
     {
           cout<<"输入a:"<<endl;
     }

    template<class T1>
    void A<T1>::input()
     {
          cin>>a;
     }

    template<class T1>
    void A<T1>::output2()
     {
          cout<<a<<endl;
     }

     template<class T2>
      class B:virtual public A<T2>
       {
       };


      template<class T3>
     class C:virtual public A<T3>
       {
      };

    int main()
      {
        A<int> *pt;
        B<int> B1;
        C<double> C1;
        int choice;
      cout<<"chioce 1 or 2?"<<endl;
      cin>>choice;
      if(choice==1)
              pt=&B1;
      else
             pt=&C1;
      pt->output1();
      pt->input();
      pt->output2();
      return 0;
    }

--------------------Configuration: 38 - Win32 Debug--------------------
Compiling...
38.cpp
E:\SoftDocument\C++\38\38.cpp(58) : error C2440: '=' : cannot convert from 'class C *' to 'class A *'
Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
执行 cl.exe 时出错.

38.exe - 1 error(s), 0 warning(s)

  • 写回答

4条回答 默认 最新

  • oyljerry 2015-05-02 14:14
    关注

    你c是double类型,a是int类型。两者不y一致。

    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器