//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"