天下

记录修行的印记

c++知识点:返回引用,前置声明,using

//1.h
#pragma once
//class std::string; 含有命名空间的话,这样使用无效,
using std::string;
string& GetString(int n); 

extern std::map<int,std::string> strings;

//1.cpp
#include "stdafx.h"
std::map
<int,std::string> strings;


/*
千万不要返回局部对象的引用。当函数执行完毕时,将释放分配给局部对象的存储空间。此时,对局部对象的引用就会指向不确定的内存。如:

const string &manip(const string &s)
{
    string ret =s;
    return ret;  //wrong:returning reference to a local object
}
4,引用返回左值。返回引用的函数返回一个左值。因此这样的函数可用于任何要求使用左值的地方。
示例见:c++ primer p215

*/
string& GetString(int n)
{
    std::map
<int,std::string>::iterator iter = strings.find(n);
    
if (iter==strings.end())
    {
        
return strings[0];
    }
    
return iter->second;
}


//main.cpp
#include "stdafx.h"

int main() 

    strings[
0= "_0";
    strings[
1= "_1";
    strings[
2= "_2";

    std::
string a = GetString(-1);

    std::
string b = GetString(1);

    system(
"pause");
    
return 0;
}

//stdafx.h
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
#pragma once
#include 
"targetver.h"
#include 
<stdio.h>
#include 
<stdlib.h>
#include 
<tchar.h>
#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS      // some CString constructors will be explicit

#include 
<atlbase.h>
#include 
<atlstr.h>
#include 
<strsafe.h>
#include 
<string>
#include 
<algorithm>
#include 
<iostream>
#include 
<vector>
#include 
<time.h>
#include 
<stdio.h>
#include 
<stdlib.h>
#include 
<assert.h>
#include 
<map>
#include 
"1.h"

posted on 2013-05-23 18:27 天下 阅读(759) 评论(0)  编辑 收藏 引用 所属分类: C/C++


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


<2013年5月>
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

导航

统计

常用链接

留言簿(4)

随笔分类(378)

随笔档案(329)

链接

最新随笔

搜索

最新评论