1
2
3
4
5
6
7
8
9
10
11
12
13
|
void Report(Animal &rAnimal) //这里不用&会怎么样? { cout << rAnimal.GetName() << " says " << rAnimal.Speak() << endl; } int main() { Cat cCat( "Fred" ); Dog cDog( "Garbo" ); Report(cCat); Report(cDog); }
A word of warning: the signature of the derived class function must exactly match the signature of the base class virtual function in order for the derived class function to be used. If the derived class function has different parameter types, the program will likely still compile fine, but the virtual function will not resolve as intended. ?这种情况属于overloading函数重载 还是override?
网上解释: inherence就是继承啊,OO里的基本概念。
|
1
2
3
4
5
6
7
8
9
10
11
| class Base { public : virtual const char * GetName() { return "Base" ; } }; class Derived: public Base { public virtual const char * GetName() { return "Derived" ; } }; |
There may be cases where you want a Base pointer to a Derived object to call Base::GetName() instead of Derived::GetName(). To do so, simply use the scope resolution operator:
1
2
3
4
5
6
7
| int main() { Derived cDerived; Base &rBase = cDerived;//Quetion: what's this? // Calls Base::GetName() instead of the virtualized Derived::GetName() cout << rBase.Base::GetName() << endl; } |
You probably won’t use this very often, but it’s good to know it’s at least possible.
http://www.learncpp.com/cpp-tutorial/142-function-template-instances/
Another example
Let’s do one more example of a function template. The following function template will calculate the average of a number of objects in an array:
1
2
3
4
5
6
7
8
9
10
| template < class T> T Average(T *atArray, int nNumValues) //这里为什么是T *atArray 而不用T &atArray { T tSum = 0; for ( int nCount=0; nCount < nNumValues; nCount++) tSum += atArray[nCount]; tSum /= nNumValues; return tSum; } |
Now let’s see it in action:
1
2
3
4
5
| int anArray[] = { 5, 3, 2, 1, 4 }; cout << Average(anArray, 5) << endl; double dnArray[] = { 3.12, 3.45, 9.23, 6.34 }; cout << Average(dnArray, 4) << endl; |
This produces the values:
double
& operator[](
int
nIndex)
{
assert
(nIndex >= 0 && nIndex < m_nLength);
return
m_pdData[nIndex];
}
No comments:
Post a Comment