所以我正在为类做调试作业。我们不允许进行任何严重的代码更改。我的代码是:
#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: In function main':
quiz2.cpp:(.text+0x54): undefined reference to
base_rec::showme()' collect2: error: ld returned 1 exit status
我不完全确定这里的问题是什么。有什么建议吗?
首先:
brp[2] = new g_rec;
将超出范围,因为数组索引从 0
开始
其次:
showme
在base_rec
中没有定义。如果真的要调用派生类的方法,需要声明为virtual。
第三,你的代码中有几个语法错误:
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;
}
如果你真的想看看多态是如何工作的,你需要在base_rec
类中将showme
声明为virtual
。然后当你通过基类指针调用它时,它会向你展示多态行为。例如:
class base_rec
{
public:
base_rec (std::string contentstr):str(contentstr){}
virtual void showme(){ std::cout << "base class showme";}
std::string str;
};
我是一名优秀的程序员,十分优秀!