标签: virtual-functions

为什么非纯虚方法必须在基类中定义?

在这种特殊情况下,为什么我必须在基类中定义非纯虚方法以避免链接器错误?

这会产生链接器错误:

class A
{
  public:
  virtual ~A(){}
  virtual void foo() = 0;
  virtual void bar();
};

class B : public A
{
  public:
  void foo()
  {
  }
  void bar()
  {
  }
};

int main()
{
    B b;
}
Run Code Online (Sandbox Code Playgroud)

输出:

/tmp/cc5E8Tit.o: In function `A::~A()':
:(.text._ZN1AD2Ev[_ZN1AD5Ev]+0x13): undefined reference to `vtable for
A' /tmp/cc5E8Tit.o:(.rodata._ZTI1B[_ZTI1B]+0x10): undefined reference
to `typeinfo for A' collect2: error: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)

但如果我在类中定义 bar 方法,A它链接正常:

class A
{
  public:
  virtual ~A(){}
  virtual void foo() = …
Run Code Online (Sandbox Code Playgroud)

c++ virtual-functions linker-errors pure-virtual

0
推荐指数
1
解决办法
708
查看次数

覆盖虚函数返回类型不同并且在数据结构中不是协变的

当我尝试编译时,出现一个奇怪的错误:“覆盖的虚函数返回类型不同并且不是协变的”,我认为问题出在 Node.js 上。我认为这BTree<T>::NodeBSTree<T>::Node.

基类:

#ifndef BINARY_TREE_H
#define BINARY_TREE_H

template < typename T >
class BTree {
protected:
    struct Node {
        T key;
        Node* left;
        Node* right;

        Node() {}
        Node(
            const T& key,
            Node* left = nullptr,
            Node* right = nullptr)
            : left(left), right(right), key(key) {}
    };
public:
    BTree();
    virtual ~BTree();
    virtual Node* search(const T& key);


private:
    Node* search(const T& key, Node* root);

private:
    Node* root;
};

template < typename T >
typename BTree<T>::Node* BTree<T>::search(const T& key, …
Run Code Online (Sandbox Code Playgroud)

c++ oop virtual-functions class

0
推荐指数
1
解决办法
70
查看次数

这个包含 reinterpret_cast 模板类型之间的 C++ 代码定义良好吗?

https://onlinegdb.com/RU3bYEfCB

#include <iostream>
using namespace std;

//--------------------Foo------------------
template<int Index>
class Foo {
 public:
  Foo(string first, string second, string third) {
    foo_[0] = first;
    foo_[1] = second;
    foo_[2] = third;
  }

  string operator()() const {
    return foo_[Index];
  }

 private:
  string foo_[3];
};

//---------------------Bar------------------
class BarBase {
 public:
  virtual string operator()() const { return "BarBase"; };
};

template<int Index>
class Bar : public BarBase {
 public:
  Bar(string first, string second, string third) {
    bar_[0] = first;
    bar_[1] = second;
    bar_[2] = third; …
Run Code Online (Sandbox Code Playgroud)

c++ inheritance virtual-functions reinterpret-cast

0
推荐指数
1
解决办法
57
查看次数

C++20 中 constexpr 虚函数的优点是什么?

我可以很容易地说,通过将函数声明为constexpr,我们可以在编译时对其进行评估,这可以节省运行时的时间,因为结果已经生成了。

另一方面,虚函数需要在运行时解析。因此,我想我们无法摆脱解决过程。由于函数的机​​制,只能快速获取结果constexpr

函数还有其他好处吗constexpr virtual

c++ virtual-functions constexpr c++20 constexpr-function

0
推荐指数
1
解决办法
691
查看次数

如何克服存储库模式中的对象切片?

我有以下代码:

#include <iostream>

class AnimalRepository {
public:
    virtual ~AnimalRepository() = default;

    virtual auto makeSound() -> void {
        std::cout << "Null" << std::endl;
    }

};

class CatRepository: public AnimalRepository {
public:
   
    auto makeSound() -> void override {
       std::cout << "Meow" << std::endl;
    }

};

class DogRepository: public AnimalRepository {
public:

    auto makeSound() -> void override {
        std::cout << "Woof" << std::endl;
    }

};

class Animal {
public:
    explicit Animal(const AnimalRepository& repository)
            : repository(repository) {
    }

    auto makeSound() -> void {
        return …
Run Code Online (Sandbox Code Playgroud)

c++ overriding virtual-functions repository-pattern object-slicing

0
推荐指数
1
解决办法
83
查看次数

虚方法仅适用于基类指针

下面是C++中虚拟函数最简单的例子:

#include <iostream>

class A {
public:
    virtual void f() {
        std::cout << "A";
    }
};

class B : public A {
public:
    void f() {
        std::cout << "B";
    }
};


int main() {
    {
        // calls f() in derived class
        A* a = new B();
        a->f();
    }
    {
        // calls f() in base class
        A a = B();
        a.f();
    }
}
Run Code Online (Sandbox Code Playgroud)

这个程序的输出是BA.我期待它BB,即在任何情况下调用基类.为什么使用基类指针会有所不同?我没有在标准中找到解释.

c++ virtual-functions

-1
推荐指数
1
解决办法
894
查看次数

继承:Child使用父虚函数而不是自己的虚函数

我有继承这个问题,我无法解决这个问题.我有三个班,他们之间有父母关系.它们都具有calcForces()函数.

class Object {
public:
    virtual void calcForces();
};


class Boat : public Object {
public:
    virtual void calcForces();
};


class Sailboat : public Boat {
public:
    void calcForces(Wind wind);
};
Run Code Online (Sandbox Code Playgroud)

现在我的问题是II有一个创建为Sailboat的对象(并将其保存在Object-pointer中),但是当我调用calcForces()时,我最终在Boat :: calcForces()中,而不是Sailboat :: calcForces().我究竟做错了什么?

这是我对函数的调用:

(*this->object_ptr_arr[i]).calcForces();    //'object_ptr_arr' is of type 'Object**'
Run Code Online (Sandbox Code Playgroud)

c++ inheritance virtual-functions

-1
推荐指数
1
解决办法
148
查看次数

无法实例化具有多个继承的抽象类C ++

C2259实例化从其他类继承的类时出现编译器错误,这些类具有抽象方法。

继承方案有点怪异和不透明,但由于问题的某些限制,我需要以这种方式进行操作。

继承方案如下:

class A
{
public:
    enum Animal { CAT, DOG };
    enum Color { RED, GREEN };
    enum Food { MEAT, FISH };

protected:
    virtual Animal animal() const = 0;
    virtual Color color() const = 0;
    virtual Food food() const = 0;
};

class B: public A
{
Animal animal() const { return CAT; }
};

class C: public A
{
Color color() const { return GREEN; }
};

class D: public A
{
Food food() …
Run Code Online (Sandbox Code Playgroud)

c++ inheritance abstract-class virtual-functions multiple-inheritance

-1
推荐指数
1
解决办法
104
查看次数

使用在堆栈上创建的对象调用虚拟函数

我有一个带有两个函数的简单CTest类- func()virtualFunc()。我仅出于测试目的而在堆栈上创建一个对象,并希望观察其行为。我确实意识到我们应该new在堆上使用关键字创建一个对象,但是我对知道对象在堆栈上时虚函数的行为很感兴趣。

使用我当前拥有的代码,当我尝试调用虚拟函数时会导致Seg Fault。谁能告诉我为什么虚拟功能导致段错误而非虚拟功能却没有?

class CTest {
    public:
        void func() {
            printf("function was called.\n");
        }   
        virtual void virtualFunc() {
            printf("virtual function was called.\n");
        }   
};

int main (int argc, char ** argv) {
    CTest * obj = NULL;

    obj->func(); // this would print "function called" as what's inside the func()

    obj->virtualFunc(); 
    //line above results in segfault because C *obj is on stack; 
    //You would need to allocated obj on the heap for the virtual function …
Run Code Online (Sandbox Code Playgroud)

c++ virtual-functions segmentation-fault

-1
推荐指数
1
解决办法
34
查看次数

从base调用虚方法

我正在尝试为MigraDoc创建一个基于此示例的库,它支持不同类型的文档.我的想法是创建一个基类,使用虚拟方法CreatePage()(负责页面布局的方法).但是,这个概念CreatePage()应该从一个被用户调用的方法中调用CreateDocument().唉,它可以覆盖CreatePage(),但它并不意味着直接调用.它看起来像这样:

public class DocumentWriter
{
    private Document document;

    public virtual void CreateDocument(IDocumentArgs args)
    {
       document = new Document();

       DefineStyles();
       CreatePage();
       FillContent(args);
    }

    public virtual void CreatePage()
    {
        // Create page layout here
    }

    // Remaining code skipped for readability...
}
Run Code Online (Sandbox Code Playgroud)

但是如果创建继承的类,哪个覆盖CreatePage(),那么将调用哪个方法CreateDocument()

  • 原始的虚拟(非重写)方法
  • 覆盖的方法 CreatePage()

c# virtual-functions

-2
推荐指数
1
解决办法
66
查看次数

没有实现虚函数

我想问一下,没有实现虚函数有问题吗?例如:

class Function { 
public: 
    virtual ~Function() {} 
    virtual double value(double x) const = 0; 
    virtual Function* clone() const = 0; 
protected: 
    virtual void print(ostream& os) const = 0; 
    friend ostream& operator<<(ostream& os, const Function& f); 
}; 
Run Code Online (Sandbox Code Playgroud)

在Function的派生类中,如果没有实现clone,它会给出编译错误吗?或者,如果我尝试调用derived.clone(),它会是运行时错误吗?

c++ inheritance abstract-class virtual-functions

-3
推荐指数
1
解决办法
777
查看次数