0
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): undefined reference to `base_rec::showme() const' collect2: error: ld returned 1 exit status。

我该如何解决它!showme() 在 base_rec 中定义

4

1 回答 1

1

您的程序存在 3 个问题。首先,在 C++ 中定义覆盖的方式是使基类中的函数成为纯虚拟函数。然后您可以覆盖子类中的实现。由于您正在定义一个没有定义的基类类型对象数组,因此 C++ 假定您要调用基类的函数。

第二个问题是数组索引超出范围。在大小为 2 的数组中不能有索引 2。

最后,当您使用 new 在堆上分配内存时,您还需要使用 delete 释放它。不这样做可能会导致内存泄漏。

#include <string>
using namespace std;

class base_rec {
public:
    base_rec():str(" "){};
    base_rec(string contentstr):str(contentstr){};
    virtual void showme() const=0;
    virtual ~base_rec(){};
protected:
    string str;

};

class u_rec:public base_rec {
public:
    u_rec():base_rec("undergraduate records"){};
    void showme() const { 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() const { cout << "showme() function of g_rec class\t"
                         << str << endl;}
};

int main() {
    base_rec *brp[2];
    brp[0] = new u_rec;
    brp[1] = new g_rec;
    for (int i=0; i<2; i++) {
        brp[i]->showme();
    }
    for (auto b: brp) {
        delete b;
    } 
}

于 2021-04-30T00:16:53.310 回答