2014-02-20 30 views
1

我看到一些例子,像基類中的函數被聲明爲純函數(如虛函數),並且在派生類中聲明(如虛函數)並實現。在第二種情況下(我現在正在這樣做),基類不聲明函數,只聲明派生類聲明(不是虛函數)並執行。這兩個選項有什麼區別?在派生類中定義函數而無需在基類中聲明

回答

0

在第一種情況下(並且順便說一下,派生類中的虛擬聲明是多餘的 - 虛擬化是繼承的),可以使用指針Base* p = new Derived()來調用p->the function

在第二種情況下,您無法使用p調用該函數。您只能使用Derived* pp = new Derived(),然後使用pp->the function

0

如果基類根本沒有聲明函數,那麼該函數不能通過基類的類型調用。例如:

struct Base1 
{ 
    virtual ~Base1() {} 

    virtual void foo() const = 0; 
}; 


struct Derived1 : Base1 
{ 
    virtual void foo() const override { std::cout << "Foo!\n"; } 
}; 

int main() 
{ 
    Base1 *p = new Derived1(); 
    p->foo(); // Works fine 
    delete p; 
} 

比。

struct Base2 
{ 
    virtual ~Base2() {} 
}; 


struct Derived2 : Base2 
{ 
    virtual void foo() const { std::cout << "Foo!\n"; } 
}; 

int main() 
{ 
    Base2 *p = new Derived2(); 
    p->foo(); // Compiler error: no foo() in Base2 
    delete p; 
} 
0

不同的是,在第一種情況下,你有polimorphism而在第二種情況下,你有沒有它。

考慮下面的例子

第一殼體

#include <iostream> 

struct B 
{ 
    virtual void f() const = 0; 
    virtual ~B() {} 
}; 


struct D1 
{ 
    void f() const { std::cout << "It's me, D1!" << std::endl; } 
}; 


struct D2 
{ 
    void f() const { std::cout << "No, it's me, D2!" << std::endl; } 
}; 


void g(const B &b) 
{ 
    b.f(); 
} 

int main() 
{ 
    D1 d1; 
    g(d1); 

    D2 d2; 
    g(d2); 
} 

和第二殼體

#include <iostream> 

struct B 
{ 
}; 


struct D1 
{ 
    void f() const { std::cout << "It's me, D1!" << std::endl; } 
}; 


struct D2 
{ 
    void f() const { std::cout << "No, it's me, D2!" << std::endl; } 
}; 


void g(const B &b) 
{ 
    // b.f(); // compilation error 
} 


void g1(const D1 &d1) 
{ 
    d1.f(); 
} 

void g2(const D2 &d2) 
{ 
    d2.f(); 
} 

int main() 
{ 
    D1 d1; 
    g1(d1); 
    g(d1); // function f will not be called 
    //g2(d1); // compilation error 

    D2 d2; 
    g2(d2); 
    g(d2); // function f will not be called 
    //g1(d2); // compilation error 
} 
相關問題