您的位置:首页 > 其它

关于引用和指针的区别以及模板使用的练习

2014-02-20 21:08 387 查看
//以下为引用变量为形参的函数和指针变量为形参的函数
#ifndef TEST_PA_H
#define TEST_PA_H
#include<stdio.h>
#include<QObject>
#include<iostream>
using namespace std;
//模板开头必须有template参数 无论是类还是函数
template<typename M>

class Test_Pa
{
//由于linux中模板类的实现必须在同一个类的头函数里,所以将test_pa_dis的程序复制过来
public:
Test_Pa(M a, M b)
{
this->a = a;
this->b = b;
pa = &a;
pb = &b;
}
//pt函数为指针为形参的函数,作用是交换指针pta和ptb值,若无&则不能实现功能,因为没有&就只是对pa和pb的副本进行操作,对他们本身无影响
void pt(M *&pta , M *&ptb)
{
M *ptc;
ptc = pta;pta = ptb;ptb = ptc;
}
//ref函数说明了引用的作用,引用实质上就是变量的别名,所以此处形参实际上就是实参的别名,所以对形参操作就是对实参操作
void ref(M &ra, M &rb)
{
M rc;
rc = ra; ra = rb; rb = rc;
}

void dis_zhizhen()
{
pt(pa,pb);
cout <<"zhizhen :*pa = "<<*pa<<",*pb = "<<*pb<<endl;
cout <<"zhizhen :a = "<<a<<",b = "<<b<<endl;
}

void dis_yinyong()
{
ref(a,b);
cout <<"yinyong :a = "<<a<<",b = "<<b<<endl;
}
protected:
M a;
M b;
M *pa;
M *pb;
};

#endif // TEST_PA_H

//main函数实现
#include "mainwindow.h"
#include <iostream>
#include <QApplication>
#include "test_pa_dis.h"
using namespace std;
int main(int argc, char *argv[])
{
Test_Pa<float> test_pa(3.9,4.9);
test_pa.dis_zhizhen();
test_pa.dis_yinyong();
return 0;
}

最后显示结果为:

zhizhen :*pa =4.9,*pa = 3.9//指针交换成功
zhizhen :a = 3.9, b = 4.9//a和b并没有进行交换




yinyong :a = 4.9, b = 3.9//因为对a和b进行操作,所以a和b交换成功 .
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: