【问题标题】:C++ abstract base class calling own pure virtual function results in "Undefined reference"C++ 抽象基类调用自己的纯虚函数导致“未定义引用”
【发布时间】:2012-03-26 19:19:02
【问题描述】:

我有一个基类:

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(),但是我如何让它像正常调用虚拟调用一样调用函数? IE。如何让它从 Foo 内部调用 Bar::getClassName()?

编辑:忘记继承了

【问题讨论】:

  • 调用代码在哪里?可以贴一下吗?
  • 至少在您上面的代码中,Bar 也不是从 Foo 派生的。
  • 如果你在 Base 类中声明 getClassName 为 public,那么它不应该在 Derived 类中也是 public 吗?
  • 您的代码在经过适当修改后不会出现来自g++ -ansi -pedantic -Werror -Wall 的错误。你用的是什么编译器?
  • 不可重现。 ideone.com/h1uIl

标签: c++ function virtual abstract-class


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    有两件事是未定义的:

    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
    

    【讨论】:

      【解决方案3】:

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

      class bar: public foo { ...
      

      【讨论】:

      • 这是一个错字。抱歉,我输入了示例。
      • @Brian - 你应该总是复制/粘贴。
      猜你喜欢
      • 2013-07-03
      • 2013-06-29
      • 2019-04-20
      • 2013-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-21
      相关资源
      最近更新 更多