C + + Ask self-answer

Source: Internet
Author: User
Tags traits

1. Why is a class on a derived hierarchy the same as a virtual function in the virtual table of each class?

Because: the call to the virtual function is made by a virtual pointer + offset address, because the call to the virtual function is this way, so the offset value for the same virtual function must be the same. 2. What are the ways to prevent object slicing?

You can define a base class as pure virtual Class 3. Why does the virtual mechanism inside the constructor not work? A. If a virtual function called by an intermediate constructor is part of a derived class at the constructor call level, there is a problem because the derived class is initialized.
B. Each constructor on the call hierarchy causes the virtual pointer to point to the virtual table of the class to which the constructor belongs, whereas the final virtual pointer of the object is determined by the last called constructor (generational the smallest class), and if a virtual function is called in the middle-level constructor, the virtual pointer that is set by the current constructor is the virtual table So the virtual function that is called is also its own function. 4. Why must a pure virtual destructor have a function body?  Because the destructor of the base class is always called by the destructor of the quilt class, if there is no function body, we don't know how to deconstruct a pure virtual class.    5. What happens if a derived class does not redefine the pure virtual function of the base class? The derived class cannot be instantiated. 6. Why the virtual mechanism in the destructor does not work.

Because the class that the virtual function belongs to may have been deleted.    7. Why you need to be extra careful when using dynamic_cast. Because dynamic_cast is used for down-type conversions, the result of the operation is not always successful, and the pointer value returned in the case of a failure is zero, and if continued use is coredump. 8. Why perform a down-type conversion on a class hierarchy that does not have a virtual function, use static_cast better than dynamic_cast because dynamic_cast uses the type information inside the virtual table, so unreasonable, even if there is no virtual table, the extra calls result in less efficiency.     9. Why the header file rules: Do not put the allocation of storage unit things to the head file? Allocation storage unit must specify a name, two header files will be included multiple times, if not using the weight of the macro, it will result in multiple definitions of the error, on the other hand, there is a row of macros, because multiple units are visible, how to coordinate and synchronize access to the block storage is also a problem. What's wrong with the Setjump and longjump of the 10.c language in C + +?
A. Tight coupling of savepoint and return points
B. Destructors are not called. Imagine if the destructor has close files, closes the network connection, frees up memory, and so on.      What are the benefits of 11.c++ 's anomaly mechanism? Decoupling the business logic code from the error handling code makes the code structure clear and easy to understand. 12. Why does the type conversion constructor not work in the exception handling mechanism????? , perhaps because the exception handler needs to be more primitive, more realistic, and more specific information, if the conversion occurs, the information is likely to be compromised. . catch (...)       What is the meaning of existence? Releasing the resource this layer, with the throw with no parameters, can pass the exception to the previous level, the upper level can continue to get exception information for processing.        14. What happens if the exception object is thrown, and the destructor throws an exception? This layer of processor will not handle the exception, if there is no previous processor, then terminate will be called, if there is a processor, the upper layer can catch this exception, but this situation is considered bad design or coding. 15. What if an exception is thrown inside the constructor, because the destructor is not called?
A. You can do an exception capture inside the constructor to free up resources!
B. You can also encapsulate pointers that need to release resources into objects, and then place them as member variables in the class, because the member variable is an object, so it calls its constructor before the constructor, so if you throw an exception at this time, the stack will release the successfully constructed object.  16. Why it is best not to derive your own exception class directly from exception.        Because the exception class does not have a constructor that receives a string, it should inherit from its subclass Runtime_error or Logic_error.  17. What happens if the thrown exception is not included in the exception specification?       unexpected will be called.   18. Rules for using exception mechanisms      a. Do not throw an exception in the interrupt handler, because the interrupt code is independent     &NBSP;B. Simple program without exception      c. Do not use exceptions as process controls.     &NBSP;D. Exceptions that can be handled due to early processing     &NBSP;E. Avoid exception specification in template functions because exception types cannot be predicted       F. If the exception is only used by this class, its definition should be placed in the namespace of the class      g. Deriving from the standard exception class is a friendly  19. What is the significance of designing an assert?       Verify the correctness of the design, the only reason for the assertion failure is the program logic bug;   20. Why write unit tests?      Process continuous testing from the code level.  21. Why do you write unit tests first?        Help developers make full-name considerations before starting to write business code.  22. What does the unit test pass represent?        Understand the need.       Meet the requirements.    23. Why can I manipulate standard input and output, files, memory, and strings as streams?      because they all conform to the characteristics of the flow operation.  24. How to use string flow to implementData type transfer?       template <class t> T stringto (const string & str)
{
T x;
Istringstream inStr (str);
instr>>x;
return x;
}
Template <class t> string toString (const T & T)
{
Ostringstream Ostr;
ostr<<t;
return Ostr.str ();}    25. How to use string flow to implement floating point number splitting. void splitdouble (const string & strdouble, int & Pre, double & aft)
{
Istringstream Istrdoub (strdouble);
istrdoub>>pre>>aft;
}                                                                                                                                                                                    &NBsp  26. What are the format controls for the output stream       27. Why is there a manipulation operator?     Because manipulation operators are easier to write than formatting functions.  28. What are the corresponding operator operators?    29. Why a member template function cannot be declared as a virtual function.      Because, when the compiler resolves the class, you want to know the size of the virtual table, and if you allow the member template virtual function, you must know in advance the number of instantiated versions that are caused by all the member function calls, which requires scanning all project files, very inflexible, Especially in the case of multi-project files.  30. Why do template parameter defaults for templates have to appear everywhere?      ...?  31. Why are the parameters of a template function declared by a single template parameter, which are defined by the template parameters, when called, even if the parameters of the given different types have the path of automatic conversion, why do you want to give an error.      does not conform to the template function declaration, the template function that is used to instantiate is not found, and the automatic type conversion step is not reached at all.   32. The difference between a class member function pointer and a normal function pointer    a. class member function pointers are functions that need to point to a certain class of qualified namespaces, so you must use the class name to qualify void when declaring (ClassName::* funcname) (paramlist)    b. Because a class member function is required to be called through a class object to set the this pointer, the call to the member function pointer is also required objectname.*pfunc    C. The member function pointer, which points to the specified argument list and return value under a certain class of namespaces, requires that the corresponding class member function pfunc=&classname::funcname 33 be selected at the time of assignment. What is a semi-ordered template       Take the most special template (similar to the type of exception), but sometimes there is no degree of specificity of the most, there are multiple side-by-side to appear ambiguous, compile error.  34. When a template is displayed, you must replace the original template parameter type with a special type, and if you encounter a const, you need to fix it.  35.template<> Note that all parameters have been customized, Template<class t> the T parameter has not yet been specificOf.   36. Why is the template class instantiated only by the called member function?      Easy, save resources wow  37. Function templates cannot be customized to be overloaded.  38. Because the template class is being re-implemented with member functions, the more specific it is, the greater the code effort. However, you can reduce the amount of code by using the following techniques.       The types that need to be customized are divided into categories, and then a full specificity is made for each category, and the other types below that category derive from this specificity        such as:      template <class t>class stack;      //full Special             Template<> class stack<void *>      //partial special for other pointers     & nbsp Template<class t>   class stack<t *>: Private stack<void *> 39. But when the compiler encounters an identifier, what information must be determined, and why?        You must determine the type, scope       know the type to determine the length and other associated information, and know the scope to determine whether the identifier appears in the correct place.  40. Feature class.        For example, a class that needs to draw a portrait of a person, which needs to draw different organ features according to the object being manipulated, can use the feature class technique.        Assume the operation of the class of portrait painting for Drawing eyes, nose, mouth.             Then define several classes, big eyes, small eyes, nose, nose, small mouth, big mouth       Then define the feature classes of several objects, Set feature name in feature class, Beauty feature Class (Eye feature class for large eyes, nose feature class for pretty nose, mouthBar characteristic class for small mouth), ugly female characteristic class (eye characteristic class for small eyes, nose characteristic class for collapsed nose, mouth characteristic class for small mouth)       The last action class first sets the feature type based on the feature class represented by the template type, followed by the direct Operation feature type.          also: #include <iostream>

using namespace Std;
Milk Products
Class Milk
{
Public
Friend Ostream & operator << (Ostream & os,const Milk &)
{
return os<< "Milk";
}
};
Compressed Milk Products
Class Condensedmilk
{
Public
Friend Ostream & operator << (Ostream & os,const Condensedmilk &)
{
return os<< "Condensedmilk";
}
};

Honey type
Class Honey
{
Friend Ostream & operator<< (Ostream & os,const Honey &)
{
return os<< "Honey";
}
};

Biscuit class
Class Cookies
{
Friend Ostream & operator<< (Ostream & os,const Cookies &)
{
return os<< "Cookies";
}
};



Define several visitor classes
Bear Class
Class Bear
{
Public
Friend Ostream & operator<< (Ostream & Os,const bear&)
{
Return os<< "Big Bear";
}
};

Kids Category
Class Boy
{
Public
Friend Ostream & operator << (ostream & OS, const Boy &)
{
Return os<< "Little boy";
}
};

Primary traits template (empty template can hold all normal types)
Template <class guest> class guesttraits;

The traits class of special
Template<> class Guesttraits<bear>
{
Public
typedef condensedmilk BEVERAGE_TYPE;
typedef Honey SNACK_TYPE;
};

Template<> class Guesttraits<boy>
{
Public
typedef Milk BEVERAGE_TYPE;
typedef cookie Snack_type;
};

Class Mixeduptraits
{
Public
typedef Milk BEVERAGE_TYPE;
typedef Honey SNACK_TYPE;
};


Driver class
Template<class Guest,class traits=guesttraits<guest> >
Class Bearcorner
{
Guest theguest;
typedef typename TRAITS::BEVERAGE_TYPE Beverage_type;
typedef typename TRAITS::SNACK_TYPE Snack_type;
Beverage_type Bev;
Snack_type snack;
Public
Bearcorner (const Guest & G): Theguest (g) {}
void Entertain ()
{
cout<< "Entertaining" <<theguest
<< "Serving" <<bev
<< "and" <<snack<<endl;
}
};
int main (int argv,char * * args, char * * env)
{
Boy Boy;
Bear Bear;
bearcorner<boy> bc1 (boy);
Bc1.entertain ();
Bearcorner<bear> BC2 (Bear);
Bc2.entertain ();
Bearcorner<boy,mixeduptraits> BC3 (boy);
Bc3.entertain ();

return 0;} 42. Feature class composition strategy, implementation of policy classes, such as the above portrait, can be converted to the image by the strategy of the portrait and so on. 43. Advanced implementation of Object Count # include <iostream>

using namespace Std;

Template<class t>
Class Objcount
{
static int cnt;
Public
Objcount () {++cnt;}
Objcount (const objcount<t> & CNT) {++cnt;}
~objcount () {--cnt;}
static int GetCount () {return CNT;}
};

Template<class t> int objcount<t>::cnt=0; Class Testcnt1:public objcount<testcnt1>{};//parent class unique class Testcnt2:public objcount<testcnt2>{};//parent class Unique int Main (int Argv,char * * args, char * * env)
{
TestCnt1 t11,t12;
TestCnt2 t21,t22;
cout<< "testcnt1::getcount=" <<testcnt1::getcount () <<endl;
cout<< "testcnt2::getcount=" <<testcnt2::getcount () <<endl;
return 0;} About bind1st/bind2nd related class unary function class, two-tuple function class, binder2nd/binder1st general unary function and two-tuple function inherit from unary function class, two-tuple function class, in which the function parent class exists meaning to unify the parameter type name and return type name, For unified access to the external interface. The bind2nd function converts a generic two-tuple function object to a binder2nd-unary function object, and the call overload of the binder2nd object invokes the incoming two-tuple function object. Since the first parameter received by bind2nd is a const-qualified constant object, the operator () reload of the incoming two-tuple function object must be const-qualified.

C + + Ask self-answer

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.