C++ 数组引用传递与指针传递

#include <iostream>
#include <string>
#include <string.h>

using namespace std;
class SourceFile
{   
public: 
    template<int N>
        //这来两个构造函数编译器能区分? __FILE__ 调用哪一个??
    inline SourceFile(const char (&arr)[N])
        : data_(arr),
          size_(N-1)
    {
		cout << "consturct ref" << endl;
        const char* slash = strrchr(data_, '/');//返回最后一个 '/'
        //截取的文件名
        if(slash) 
        {
            data_ = slash + 1;
            size_ = static_cast<int>(data_ - arr );
        }
    }
    explicit SourceFile(const char* filename)
        : data_(filename)
    {
		cout << "consturct point" << endl;
        const char* slash = strrchr(filename, '/');
        if(slash)
            data_ = slash + 1;
        size_ = static_cast<int>(strlen(data_));
    }
    const char* data_;
    int size_;
};


int main(int args, char **argv)
{
	const char arr1[10] = "abc/cba";
	const char arr2[20] = "sssssssssssssssss";
	const char arr3[20] = "xxxxxxxxxxxxxxxxx";
	SourceFile s1=arr1;
	SourceFile s2(arr2);
	SourceFile s3=arr3;

	const char* pStr1 = "ni hoa";
	SourceFile s4(pStr1);
	return 0;
}

g++编译后生成执行文件a.out 

[le@localhost refArrAndPoint]$ nm ./a.out | grep SourceFile

0000000000400b20 W _ZN10SourceFileC1EPKc
0000000000400b9c W _ZN10SourceFileC1ILi10EEERAT__Kc
0000000000400c2c W _ZN10SourceFileC1ILi20EEERAT__Kc

0000000000400b20 W _ZN10SourceFileC2EPKc
0000000000400b9c W _ZN10SourceFileC2ILi10EEERAT__Kc
0000000000400c2c W _ZN10SourceFileC2ILi20EEERAT__Kc

编译器为我们生成了三个构造函数,两个是函数模板的
[le@localhost refArrAndPoint]$ ./a.out 
consturct ref
consturct point  //  SourceFile s2(arr2) 调用的是传指针的构造函数,说明数组默认是用指针传递,而不是引用传递
consturct ref
consturct point


如果 指针传递的构造函数,没有用explicit。。那输出都是 consturct point

总结:数组默认是用指针传递,而不是引用传递,想要引用传递,要么就不能有传指针的构造函数,要么就要像上面一样用explicit分开出来(好像有点麻烦)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值