【问题标题】:It is referenced and I still get undefined reference issue它被引用了,我仍然得到未定义的引用问题
【发布时间】: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],所以可用的索引只有01
  • showme()base_rec声明。你告诉编译器有这样一个函数。但它没有定义。你从来没有告诉编译器什么base_recshowme()版本应该做什么。

标签: c++ polymorphism


【解决方案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;
    } 
}

【讨论】:

    猜你喜欢
    • 2017-12-23
    • 2011-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 2014-05-06
    • 1970-01-01
    相关资源
    最近更新 更多