[2016-04-23] [Some things about C + + class templates]
Definitions (about class templates and template classes)
Use
The
- instantiation must specify a type,
- with the class name followed by the
< type,
to indicate the type
-
array <int> ; a
- Note
- No specified type is not instantiated,
- A variable that is not instantiated is not available!!!
template <typename T> T a;
cin>>a;//‘ERROR:a还没有实例化‘,
- At the same time the above t A; this usage can only appear in the class, because the class theorem has not been instantiated, outside the class is not allowed!!!
Overloading of operators
- Overloading of ordinary operators
- As with other classes of overloads
- << and >> heavy-duty
Is the statement template T does not play a role, unrecognized, here because the ability problem can not be figured out, but can find a solution, (tube He why, learn the right posture is OK)
- Now that we can't recognize it, we'll just let it be recognized, okay?
- The method is to overload the function into a function outside the class (if you want to access private, declare it as friend),
- Then define the type of the array when declaring the variable (see array A below, not array a)
Here is the function declaration called function template of << overloaded
friend ostream & operator<<(ostream &os,const Array<T> & a){
os<<"hongyang\n";
return os;
}
- Another problem is that the declaration and definition of the entire friend function must be written in the class.
- The declaration is written inside, defining the outside of the write band class, which is wrong!!!
- The reason is that if implemented outside of the class, the outside T and T in the inside is not the same T, the equivalent of defining a new template T (and the class inside the T is not a thing),
- A bit around, do not understand to jump over, learn the right posture is good
- If you simply want to define outside the class, there is no way to do so, that is, in this function does not use the class's data members, by using the class member function to achieve the purpose of accessing the data
friend ostream & operator<<(ostream &os,const Array<T> & a){
// os<<a.Date;错误!!!
os<<a.getDate();
return os;
}
Information:
Http://www.cnblogs.com/xkfz007/articles/2534322.html
From for notes (Wiz)
[2016-04-23] [Some things about C + + class templates]