1

所以我正在为班级做一个调试作业。我们不允许进行任何严重的代码更改。我的代码是:

#include <string>
#include <iostream>
#include <sstream>


class base_rec
{public:
  base_rec (std::string contentstr):str(contentstr){};
  void showme();
  std::string str;};

class u_rec:public base_rec
{public:
  u_rec():base_rec("undergraduate records"){};
  void showme()
  {std::cout<<"showme() function of u_rec class\t" <<str<<std::endl;};};


class g_rec:public base_rec
{public:
  g_rec():base_rec("graduate records"){};
  void showme()
  {std::cout << "showme() function of a g_rec class\t"<<str<<std::endl;};};



  int main()
  { base_rec *brp[2];
    brp[1] = new u_rec;
    brp[2] = new g_rec;

    for (int i=0;i<1;i++)
      {brp[i]->showme ();}

    return 0;
}

但是,每当我尝试编译它时,都会收到错误消息:

/tmp/ccFm7Xvz.o:在函数main': quiz2.cpp:(.text+0x54): undefined reference tobase_rec::showme()' collect2:错误:ld 返回 1 退出状态

我不完全确定这里有什么问题。有什么建议么?

4

1 回答 1

1

首先:

brp[2] = new g_rec;

将超出范围,因为数组索引从0

其次:

showmeis 里面没有定义base_rec。如果你真的想调用派生类方法,你需要将它声明为虚拟的。

第三,您的代码中有几个语法错误:

 u_rec():base_rec("undergraduate records"){}; //redundant ;
 void showme()
 {std::cout<<"showme() function of u_rec class\t" <<str<<std::endl;};
                                                     //redundant ; again
 //You can find several others.

您可以执行以下操作:

#include <string>
#include <iostream>
#include <sstream>


class base_rec
{
  public:
     base_rec (std::string contentstr):str(contentstr){}
     void showme(){ std::cout << "base class showme";}
     std::string str;
};

class u_rec: public base_rec
{
public:
    u_rec():base_rec("undergraduate records"){}
    void showme()
   {
      std::cout<<"showme() function of u_rec class\t" <<str<<std::endl;
   }
};


class g_rec:public base_rec
{
  public:
   g_rec():base_rec("graduate records"){};
     void showme()
     {
        std::cout << "showme() function of a g_rec class\t"<<str<<std::endl;
     }
};



int main()
{ 
    base_rec *brp[2];
    brp[0] = new u_rec;
    brp[1] = new g_rec;  //index starting from 0

   for (int i=0;i<1;i++)
   {
      brp[i]->showme ();
   }

   return 0;
}

如果你真的想看看多态是如何工作的,你需要在类中声明showmeas 。然后当你通过基类指针调用它时,它会向你展示多态行为。例如:virtualbase_rec

 class base_rec
 {
  public:
     base_rec (std::string contentstr):str(contentstr){}
     virtual void showme(){ std::cout << "base class showme";}
     std::string str;
 };
于 2013-04-12T00:13:36.767 回答