欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

函数的返回类型是引用类型与函数的返回类型是指针类型

程序员文章站 2023-11-06 09:29:10
``` // // main.cpp // 引用类型指明函数的返回类型 // 指针类型指明函数返回指针类型 // Created by mac on 2019/4/7. // Copyright © 2019年 mac. All rights reserved. include using name ......
//
//  main.cpp
//  引用类型指明函数的返回类型
//  指针类型指明函数返回指针类型
//  created by mac on 2019/4/7.
//  copyright © 2019年 mac. all rights reserved.
#include <iostream>
using namespace std;

//函数的返回值是个引用
int &f2(int a[],int i){
    return a[i];
}

//函数的返回值是个指针
int *f3(int a[],int i){
    return &a[i];
}

//引用变量破坏信息隐藏原则
class c{
public:
    c(){} //构造函数
    ~c(){} //析构函数
    int & getrefn(){
        return n;
    }
    
    int getn(){
        return n;
    }
private:
    int n = 2;
}c;

int main(int argc, const char * argv[]) {
    int a[]={1,2,3,4,5};
    //在右侧调用f2
    int n = f2(a, 3);
    cout<<n<<endl; //输出4
    
    //在左侧调用f2
    f2(a, 3)=6;
    for (int i=0; i<5; i++) {
        cout<<*(a+i)<<" "<<endl;
    }
    
    //右侧调用f3
    int d = *f3(a,3);
    cout<<d<<endl;
    
    //左侧调用f3
    *f3(a,3)=9;
    // 注意:此处如果写成 p<p+5 那么结果就悲剧了,想想其中的原因?
    // 因为a+5是一个常数,有个上界范围,那个p<p+5是个没有上界的恒等式,将会输出一大堆东西
    // 1 2 3 9 5 注意都有换行
    for (int *p=a;p<a+5; p++) {
        cout<<*p<<" "<<endl;
    }
    //并非单纯的数学计算
    int *p=a;
    cout<<p<<endl;    // 输出的是 0x7ffeefbff4b0
    cout<<a<<endl;    // 输出的是 0x7ffeefbff4b0
    cout<<a+1<<endl;  // 输出的是 0x7ffeefbff4b4
    cout<<p+1<<endl;  // 输出的是 0x7ffeefbff4b4
    
    //引用变量破坏信息隐藏原则
    // 私有变量n的默认值是2 通过getrefn()函数修改为10
    cout<<c.getn()<<endl; //输出2
    int &k=c.getrefn();
    k=10;
    cout<<c.getn()<<endl;//输出10
    return 0;
}

tips

  • fabs函数是求绝对值函数。需要头文件 #include <math.h> 或者#include <cmath>
  • 对于静态绑定来说,调用哪个函数是在编译阶段确定的。对于动态绑定,则要推迟到运行阶段才能确定。动态绑定是通过将成员函数声明为virtual实现的。