具有相同名称但参数和返回类型不同的虚函数

时间:2019-06-09 11:39:33

标签: c++ class inheritance virtual-functions

在一次采访中有人问我这个问题。我的答案是(3和3.6)(错误)。 请解释一下我的理解是错的

我的想法是指针 bd 将指向派生类vtable的_vptr。

派生类的Vtable将包含2个函数

double func(double) // ----->points to Derived::func()
int func(int)       // ----->points to Base::func()

因此

bd->func(2)   // will call Base::func() i.e int func(int)
bd->func(2.3) // will call Derived::func() i.e double func(double)

请说明我的理解是错误的。 另外,请说明Base::func()不是virtual时的情况。 在那种情况下,将不会有vtable吗?函数调用将如何解决?

#include <iostream>    
using namespace std;

class Base
{
private:
    /* data */
public:
    Base(/* args */){};
    ~Base(){};

    //int func(int i)     getting same answer regardless of virtual
    virtual int func(int i)
    {
        cout << "Base func()" << endl;
        return i+1;
    }
};

class Derived : public Base
{
public:
    Derived(/* args */){};
    ~Derived(){};

    double func(double d)
    {
        cout << "Derived func()" << endl;
        return d+1.3;
    }
};

int main() {
    Base* bd = new Derived();
    cout << bd->func(2) << endl;
    cout << bd->func(2.3) << endl;
    return 0;
}

预期输出:

Base func()
3
Derived func()
3.6

Actual output:
Base func()
3
Base func()
3

1 个答案:

答案 0 :(得分:1)

var shopifyAjaxAddURL = '/cart/add.js'; var shopifyAjaxCartURL = '/cart.js'; var shopifyAjaxStorePageURL = '/search'; $(document).on('submit', 'form[action="/cart/add"]:not(.noAJAX, .feedback-go_to_cart)', function(e) { var $form = $(this); //Disable add button var $btn = $(this).find('[type=submit]').attr('disabled', 'disabled').addClass('confirmation'); $btn.data('originalHtml', $btn.html()).html({{ 'products.product.adding_to_cart' | t | json }}); //Add to cart $.post(shopifyAjaxAddURL, $form.serialize(), function(itemData) { //Enable add button $btn.html(theme.icons.tick + ' ' + {{ 'products.product.added_to_cart' | t | json }}); setTimeout(function(){ $btn.removeAttr('disabled').removeClass('confirmation').html($btn.data('originalHtml')); }, 4000); var pro_hand = $. parseJSON(itemData).handle; var ajax_pro_handl ='/products/'+ pro_hand +'.js'; var pro_featured_img =''; $.getJSON(ajax_pro_handl, function(product) { pro_featured_img = product.featured_image; }); setTimeout(function(){ if($form.hasClass('feedback-add_in_modal')) { showThemeModal([ '<div id="added-to-cart" class="theme-modal align-centre top-padded" tabindex="-1">', '<div class="inner">', '<div class="container">', '<div class="cart-pop-upper">', '<a href="#" data-modal-close><i class="fa fa-close"></i></a>', '<h4>Cart</h4>', '</div>', '<h4 class="pro_titl">' + $. parseJSON(itemData).product_title + '</h4>', '<img class="image_cartpop" src="' + pro_featured_img + '"/>', '<p class="pro_varint">' + $. parseJSON(itemData).variant_title + '</p>', /*'<p>' + {{ 'products.product.popup_was_added' | t | json }} + '</p>', '<p class="content-row"><a class="circled-icon" href="/cart">'+theme.icons.tick+'</a></p>', '<p class="links"><a href="#" data-modal-close>'+{{ 'products.product.popup_continue_shopping' | t | json }}+'</a> &bull; <a href="/cart">' + {{ 'products.product.popup_checkout' | t | json }} + '</a></p>',*/ '<a href="/cart" class="checkout_btton">' + {{ 'products.product.popup_checkout' | t | json }} + '</a>', '<a href="/cart" class="pop_cart_link">View Cart</a>', '<a href="#" class="continue_shop" data-modal-close>'+ {{ 'products.product.popup_continue_shopping' | t | json }} +'</a>', '</div>', '</div>', '</div>' ].join('')); } }, 1000); //Update header summary $.get(shopifyAjaxStorePageURL, function(data){ var cartSummarySelector = '#site-control .cart'; var $newCartObj = $($.parseHTML('<div>' + data + '</div>')).find(cartSummarySelector); var $currCart = $(cartSummarySelector); $currCart.replaceWith($newCartObj); }); }, 'text').error(function(data) { //Enable add button $btn.removeAttr('disabled').removeClass('confirmation').html($btn.data('originalHtml')); //Not added, show message if(typeof(data) != 'undefined' && typeof(data.status) != 'undefined') { var jsonRes = $.parseJSON(data.responseText); window.showQuickPopup(jsonRes.description, $btn); } else { //Some unknown error? Disable ajax and submit the old-fashioned way. $form.addClass('noAJAX'); $form.submit(); } }); setTimeout(function(){ jQuery('#dropdown-cart').addClass('active'); updateDropdownCart(); },1000); return false; }); 中没有使用double的函数。您所拥有的只是指向Base的指针。因此2.3被截断为Baseint并调用2

Base::func(int i)根本不在此代码中发挥作用。

Derived::func(double d)中的funcvirtual并不重要,因为Base中的func并不Derived(签名不匹配)。将override关键字添加到override将使编译器错误立即变得清楚。