因此,我正在为类进行调试分配。我们不允许进行任何严重的代码更改。我的代码是:

#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;
}

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



我不太确定这里出了什么问题。有什么建议么?

最佳答案

首先:

brp[2] = new g_rec;

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

其次:
showmebase_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;
}

如果您真的想了解多态性是如何工作的,则需要在showme类中将virtual声明为base_rec。然后,当您通过基类指针对其进行调用时,它将显示出多态行为。例如:
 class base_rec
 {
  public:
     base_rec (std::string contentstr):str(contentstr){}
     virtual void showme(){ std::cout << "base class showme";}
     std::string str;
 };

关于c++ - 未定义的引用错误为“base_rec::showme()”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15960875/

10-11 22:10