The class People {
};
The class Student: public People {
};
Void printPeopleInfo (const People * performance, int len);
If I design a SDK, printPeopleInfo () this function is used to print class People, but if the following call
Student Student []=ten Student {/* */};
PrintPeopleInfo (students, 10);
Compiled no problem, but running stage is likely to appear problem, so I hope in printPeopleInfo () function testing, incoming parameters is People, if not (such as incoming class inherits from People), I hope to compile stage can error, is there any way to achieve?
CodePudding user response:
People define a virtual function in the parent class, student subclass rewritten, this method is used to return to the current name of the class, convenient detection,CodePudding user response:
Article 3 of the more effective c + + do not use polymorphism of array, you not that kind of idea!CodePudding user response:
Can use template# include & lt; iostream>
#include
Class A, {}.
Class B: A {};
Class C {};
Int main ()
{
STD: : cout & lt; & lt; STD: : boolalpha;
STD: : cout & lt; & lt; "A2b:" & lt; & lt; STD: : is_base_of & lt; A, B> : : value & lt; & lt; '\ n';
STD: : cout & lt; & lt; "B2a:" & lt; & lt; STD: : is_base_of & lt; B, A> : : value & lt; & lt; '\ n';
STD: : cout & lt; & lt; "C2b:" & lt; & lt; STD: : is_base_of & lt; C, B> : : value & lt; & lt; '\ n';
STD: : cout & lt; & lt; "Same type:" & lt; & lt; STD: : is_base_of & lt; C, C> : : value & lt; & lt; '\ n';
}
CodePudding user response:
Why can't add as you do,In an array, the array subscript access element is according to the element size, calculation of the offset array [I] is equivalent to * (array + I * sizeof (T)), when the derived class arrays to a base class pointer to visit again, because of the derived class and a base class size, problems lead to offset,
The class CBase
{
Public:
CBase () {}
Virtual ~ CBase () {}
};
The class CDrived: public CBase
{
Public:
CDrived () {}
~ CDrived () {}
Private:
Int m_nData;
};
Void FuncArray (const CBase arr [], int nCount)
{
STD: : cout & lt; & lt; & Arr [1] <& lt; STD: : endl;
}
Int main ()
{
CDrived arr [3].
STD: : cout & lt; & lt; & Arr [1] <& lt; STD: : endl;
FuncArray (arr, 3);
system("pause");
return 0;
}
Results:
You can see the output of two addresses are not the same
CodePudding user response: