#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分开出来(好像有点麻烦)