zoukankan      html  css  js  c++  java
  • Output of C++ Program | Set 18

      Predict the output of following C++ programs.

    Question 1

     1 #include <iostream>
     2 using namespace std;
     3 
     4 template <int N>
     5 class A 
     6 {
     7     int arr[N];
     8 public:
     9     virtual void fun() 
    10     { 
    11         cout << "A::fun()"; 
    12     }
    13 };
    14 
    15 class B : public A<2> 
    16 {
    17 public:
    18     void fun() 
    19     { 
    20         cout << "B::fun()"; 
    21     }
    22 };
    23 
    24 class C : public B 
    25 { 
    26 };
    27 
    28 int main() 
    29 {
    30     A<2> *a = new C;
    31     a->fun();
    32     return 0;
    33 }

      Output:

      B::fun()
      In general, the purpose of using templates in C++ is to avoid code redundancy. We create generic classes (or functions) that can be used for any datatype as long as logic is identical. Datatype becomes a parameter and an instance of class/function is created at compile time when a data type is passed. C++ Templates also allow nontype (a parameter that represents a value, not a datatype) things as parameters.
      In the above program, there is a generic class A which takes a nontype parameter N. The class B inherits from an instance of generic class A. The value of N for this instance of A is 2. The class B overrides fun() of class A<2>. The class C inherits from B. In main(), there is a pointer ‘a’ of type A<2> that points to an instance of C. When ‘a->fun()’ is called, the function of class B is executed because fun() is virtual and virtual functions are called according to the actual object, not according to pointer. In class C, there is no function ‘fun()’, so it is looked up in the hierarchy and found in class B.

     

    Question 2

     1 #include <iostream>
     2 using namespace std;
     3 
     4 template <int i> int fun()
     5 {
     6     i =20; 
     7 }
     8 
     9 int main() 
    10 {
    11     fun<4>();
    12     return 0;
    13 }

      Output:

      Compiler Error
      The value of nontype parameters must be constant as they are used at compile time to create instance of classes/functions. In the above program, templated fun() receives a nontype parameter and tries to modify it which is not possible. Therefore, compiler error.

      Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
      

      转载请注明:http://www.cnblogs.com/iloveyouforever/

      2013-11-27  16:53:31

  • 相关阅读:
    Qt类继承关系图
    回归Qt——写在Qt5.10发布之日
    Jdk1.7下的HashMap源码分析
    Jdk1.8下的HashMap源码分析
    八皇后||算法
    设计模式之一单例模式
    多线程之美8一 AbstractQueuedSynchronizer源码分析<二>
    多线程之美7一ReentrantReadWriteLock源码分析
    多线程之美6一CAS与自旋锁
    多线程之美5一 AbstractQueuedSynchronizer源码分析<一>
  • 原文地址:https://www.cnblogs.com/iloveyouforever/p/3446118.html
Copyright © 2011-2022 走看看