C++抽象基类调用自己的纯虚函数会导致"Undefined reference"

C++ abstract base class calling own pure virtual function results in "Undefined reference"

本文关键字:函数 Undefined reference 基类 抽象 调用 自己的 C++      更新时间:2023-10-16

我有一个基类:

class Foo {
   public:
       virtual ~Foo() {}
       static void printFoos()
       {
           std::vector<Foo*>::iterator it;
           for(it=fooList.begin();it!=fooList.end();++it)
           {
               std::cout<<"Class: "<<(*it)->getClassName()<<"n";
           }
       }
       virtual const char* getClassName()=0;
       static std::vector<Foo*> fooList;
};

以及一些派生类,例如:

class Bar : public Foo {
    public:
        Bar();
    private:
        const char* getClassName()
        {
            return "Bar";
        }
};

上面的代码给出了"对Foo::getClassName()的未定义引用",我假设这是因为代码想调用Foo::getClassName((),但我如何让它像正常的虚拟调用一样调用函数?I.E.如何从Foo内部调用Bar::getClassName()?

编辑:忘记继承

fooList中的项目必须使用newfooList[0] = new Bar()创建。正如WeaselFox所说,Bar必须继承自Foo

有两件事是未定义的:

Bar::Bar() is undefined
-   Bar();
+   Bar() {}

并且fooList未定义:

+std::vector<Foo*> Foo::fooList;

以下是更正后的程序:

test.cpp:

#include <vector>
#include <iostream>
class Foo {
   public:
       virtual ~Foo() {}
       static void printFoos()
       {
           std::vector<Foo*>::iterator it;
           for(it=fooList.begin();it!=fooList.end();++it)
           {
               std::cout<<"Class: "<<(*it)->getClassName()<<"n";
           }
       }
       virtual const char* getClassName()=0;
       static std::vector<Foo*> fooList;
};
std::vector<Foo*> Foo::fooList;
class Bar : public Foo {
    public:
        Bar() {};
    private:
        const char* getClassName()
        {
            return "Bar";
        }
};
int main()
{
    //intentionally leaked
    Foo::fooList.push_back(new Bar());
    Foo::fooList.push_back(new Bar());
    Foo::fooList.push_back(new Bar());
    Foo::printFoos();
}

输出:

Class: Bar
Class: Bar
Class: Bar

似乎bar没有继承foo。您需要声明继承:

class bar: public foo { ...
相关文章: