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
最新文章
- 尚学堂Spring视频教程(五):Spring AOP
- 关于android4.3 Intel X86 Atom System Image的下载
- Use a PowerShell Module to Easily Export Excel Data to CSV
- [原创]Scala学习:for,function,lazy
- Date的转换
- [virsh] error: unknown OS type hvm解决办法
- 欧几里德&;扩展以及求解线性方程学习总结--附上poj1061解题报告
- Delphi word编辑
- vJine 第三波 之 Lua 来袭 vJine.Lua
- Linux巡检
- mongodb数据库备份恢复
- [原创]linux简单之美(二)
- python之路 - 基础4
- WI-FI: connection through CLI
- 注解的形式与xml文件的形式完成事务管理及xml文件的配置
- Salesforce Invoking Http Callouts and Testing Http Callouts
- 在CentOS6.9 x86下编译libusb-1.0.22遇到的两个问题
- Linux服务器上监控网络带宽的18个常用命令 zz
- BZOJ 1912: [Apio2010]patrol 巡逻 (树的直径)(详解)
- BeanUtils工具类