C++ 数组引用传递与指针传递
2015-12-23 17:13
405 查看
#include <iostream> #include <string> #include <string.h> using namespace std; class SourceFile { public: template<int N> //这来两个构造函数编译器能区分? __FILE__ 调用哪一个?? inline SourceFile(const char (&arr) ) : 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分开出来(好像有点麻烦)
相关文章推荐
- C++文件读写详解(ofstream,ifstream,fstream)
- C语言宏定义##连接符和#符的使用
- C语言undefined behaviour未定义行为
- 【学习笔记】自定义关于wchar_t*的相关函数
- C,C++宏中#与##的讲解
- windows下C++多线程
- C语言开发总结(二十)
- C++文件操作——fopen/fseek/ftell/fread/fwrite/fclose等函数用法
- C++中引用与指针的区别(详细介绍)
- vc++6.0在win8.1遇到的问题
- C++异常处理
- C++ 泛型基础
- C++学习笔记-关联容器
- C++ public,protected,private继承与访问限制
- C中static的用法
- C++11 不抛异常的new operator
- 一个C++钟表小实验
- c语言
- 用C++向一个txt文档中写数据
- 二叉树的遍历C++实现