【发布时间】:2021-07-23 08:40:04
【问题描述】:
class base_rec {
public:
base_rec():str(" "){};
base_rec(string contentstr):str(contentstr){};
void showme() const;
protected:
string str;
};
class u_rec:public base_rec {
public:
u_rec():base_rec("undergraduate records"){};
void showme() { cout << "showme() function of u_rec class\t"
<< str << endl;}
};
class g_rec:public base_rec {
public:
g_rec():base_rec("graduate records"){};
void showme() { cout << "showme() function of g_rec class\t"
<< str << endl;}
};
int main() {
base_rec *brp[2];
brp[1] = new u_rec;
brp[2] = new g_rec;
for (int i=0; i<2; i++) {
brp[i]->showme();
}
}
错误信息:
main.cpp:(.text+0x58): 未定义对 `base_rec::showme() const' 的引用 collect2: error: ld 返回 1 个退出状态。
我该如何解决它! showme() 在 base_rec 中定义
【问题讨论】:
-
将
void showme() const;更改为void showme() const { } -
baserec::showme()的定义在哪里?我看到了一个声明,但没有定义。 -
您可能打算让
showme成为virtual成员。然后,您可以使用= 0将其抽象化,它不会查找定义。 -
旁注,你声明了
brp[2],所以可用的索引只有0和1。 -
showme()在base_rec中声明。你告诉编译器有这样一个函数。但它没有定义。你从来没有告诉编译器什么base_rec的showme()版本应该做什么。
标签: c++ polymorphism