स्लाइसिंग को समझने के बाद, जहां तक मुझे लगता है कि इसे पॉइंटर्स का उपयोग गतिशील चर के लिए टूटा जा सकता है। लेकिन कैसे आते हैं? उस बिंदु पर कोई टुकड़ा क्यों नहीं है? मैं खुद को सोचता हूं लेकिन मुझे यकीन नहीं है। ppet = pdog;
असाइनमेंट के बाद, पीडीओजी पेपेट के एक ही पते पर इंगित करता है। है ना?वर्चुअल फ़ंक्शन और पॉइंटर उपयोग को समझना
//Program to illustrate use of a virtual function
//to defeat the slicing problem.
#include <string>
#include <iostream>
using namespace std;
class Pet
{
public:
virtual void print();
string name;
};
class Dog : public Pet
{
public:
virtual void print();//Keyword virtual not needed, but put
//here for clarity. (It is also good style!)
string breed;
};
int main()
{
Dog vdog;
Pet vpet;
vdog.name = "Tiny";
vdog.breed = "Great Dane";
vpet = vdog;
//vpet.breed; is illegal since class Pet has no member named breed
Dog *pdog;
pdog = new Dog;
pdog->name = "Tiny";
pdog->breed = "Great Dane";
Pet *ppet;
ppet = pdog;
ppet->print(); // These two print the same output:
pdog->print(); // name: Tiny breed: Great Dane
//The following, which accesses member variables directly
//rather than via virtual functions, would produce an error:
//cout << "name: " << ppet->name << " breed: "
// << ppet->breed << endl;
//generates an error message: 'class Pet' has no member
//named 'breed' .
//See Pitfall section "Not Using Virtual Member Functions"
//for more discussion on this.
return 0;
}
void Dog::print()
{
cout << "name: " << name << endl;
cout << "breed: " << breed << endl;
}
void Pet::print()
{
cout << "name: " << endl;//Note no breed mentioned
}
आउटपुट:
The slicing problem:
name: Tiny
Note that it was print from Pet that was invoked.
The slicing problem defeated:
name: Tiny
breed: Great Dane
name: Tiny
breed: Great Dane
[ओटी]: कीवर्ड 'ओवरराइड' अनियंत्रित 'आभासी' लिखने से भी बेहतर है क्योंकि यह जांचता है कि यह वास्तव में ओवरराइड है या नहीं। – Jarod42
मैंने कभी भी कीवर्ड के रूप में ओवरराइड नहीं सुना था। क्या आप थोड़ा सा समझा सकते हैं? @ जारोड 42 – askque
http://stackoverflow.com/questions/13880205/override-in-c11 – user007