gpt4 book ai didi

c++ - 对“base_rec::showme()”的 undefined reference 错误

转载 作者:太空宇宙 更新时间:2023-11-04 11:56:41 27 4
gpt4 key购买 nike

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

#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

开始

其次:

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

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com