小编Ayr*_*lin的帖子

如何在类中的其他 vtable 指针中选择 vtable 指针?

我对此很感兴趣virtual inheritance,这件事给我带来了神秘感。让我们考虑一个例子virtual inheritance

struct Base {
    virtual void v() { std::cout << "v"; }
};

struct IntermediateDerivedFirst : virtual Base {
    virtual void w() { std::cout << "w"; }
};

struct IntermediateDerivedSecond : virtual Base {
    virtual void x() { std::cout << "x"; }
};

struct Derived : IntermediateDerivedFirst, IntermediateDerivedSecond {
    virtual void y() { std::cout << "y"; }
};
Run Code Online (Sandbox Code Playgroud)

最后,Derived应该看起来像这样:

 --------
|[vtable]| -----> [ vbase offset 20               ]
|[vtable]|---     [ top offset    0 …
Run Code Online (Sandbox Code Playgroud)

c++ virtual inheritance

5
推荐指数
1
解决办法
418
查看次数

如何在 C++ 中调用默认模板功能参数?

我想要我的模板功能

template<class function>
int probe(function call = [] (int a, int b) { return a+b; })
{
    return call(10, 10);
}
Run Code Online (Sandbox Code Playgroud)

以便能够接收指向函数的指针并稍后调用此函数。这段摘录是正确的,编译器不会抱怨错误。让我们考虑这样的程序

#include <iostream>
#include <string>

template<class function>
int probe(function call = [] (int a, int b) { return a+b; })
{
    return call(10, 10);
}

int main()
{
    std::cout << probe([](int a,int b){ return a-b;});
}
Run Code Online (Sandbox Code Playgroud)

该程序输出我所期望的:零。但是,我为这个调用明确表示了我正在传递的函数 - 我的意思是括号中的这个 lambda 表达式[](int a,int b){ return a-b;}。这很好,直到我什么也没传递 - 调用std::cout << probe();不正确,但是我预计该函数将使用 default function function call …

c++ templates template-argument-deduction

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

如果函数是虚拟的,何时不是,我如何确定将调用什么函数?

看看这个程序的摘录。

我看到cout << obj->foo();调用不是多态的。实际上,这是显而易见的,因为它没有virtual说明符。

但是我很困惑cout << ((B*)obj)->foo();为什么程序不使用B虚函数的定义而会调用第三个版本foo()

 #include <iostream> 
using namespace std; 

class A{ 
public:     
    int foo(){ return 1; } 
}; 
class B: public A{ 
public:     
    virtual int foo(){ return 2; } 
}; 
class C: public B{ 
public:     
    int foo(){ return 3; } 
}; 

int main() {  
    A* obj = new C; 

    cout << obj->foo(); 
    cout << ((B*)obj)->foo(); 
    cout << ((C*)obj)->foo(); 

    return 0;  
}
Run Code Online (Sandbox Code Playgroud)

c++ oop

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

这个"无实例"错误的解决方案是什么?

我创建了描述二叉树的新类型

data BinTree a = Null | Num a (BinTree a) (BinTree a)
deriving (Show)
Run Code Online (Sandbox Code Playgroud)

并创建了以下功能:

treehandle :: BinTree a -> Bool
treehandle a = True
Run Code Online (Sandbox Code Playgroud)

检查至少输入值.

当我输入值Null时,程序输出结果成功,但我无法输入二叉树.我这样试试:

treehandle (5 (Null) (Null))
Run Code Online (Sandbox Code Playgroud)

但获得:

<interactive>:66:13:
No instance for (Num (BinTree a1 -> BinTree a2 -> BinTree a0))
  (maybe you haven't applied enough arguments to a function?)
  arising from the literal ‘5’
In the expression: 5
In the first argument of ‘treehandle’, namely ‘(5 (Null) (Null))’
In the expression: treehandle (5 (Null) …
Run Code Online (Sandbox Code Playgroud)

haskell

2
推荐指数
2
解决办法
112
查看次数