VS2017,C++语言。
今天在编程时遇到一个很奇怪的问题,程序如下:
#include<iostream>
#include<string>
#include <vector>
using namespace std;
int main()
{
struct conf
{
char itemname[40];
char itemcontent[100];
};
char * GetInfo(vector<conf *> & conflist, const char *pitem)
{
for (auto pos = conflist.begin(); pos != conflist.end(); ++pos)
{
if (_stricmp((*pos)->itemname, pitem) == 0)
return (*pos)->itemcontent;
}
return nullptr;
}
//ServerName = 1区;
//ServerID = 100000;
conf *pconf1 = new conf;
strcpy_s( pconf1->itemname, sizeof(pconf1->itemname), "ServerName");
strcpy_s( pconf1->itemcontent, sizeof(pconf1->itemcontent), "1区");
conf *pconf2 = new conf;
strcpy_s(pconf2->itemname, sizeof(pconf2->itemname), "ServerID");
strcpy_s(pconf2->itemcontent, sizeof(pconf2->itemcontent), "100000");
vector <conf*>conflist;
conflist.push_back(pconf1);
conflist.push_back(pconf2);
char * p_tmp = GetInfo (conflist, "ServerName");
if (p_tmp != nullptr)
{
cout << p_tmp << endl;
}
//我们要释放内存,new 要对应释放,否则会造成内存泄露
vector<conf*>::iterator pos;
for (pos = conflist.begin() ;pos != conflist.end(); ++pos)
{
delete (*pos);//*pos 才是那个指针//必须自己释放
}
conflist.clear();//这个要不要都行,结束时会系统回收
system("pause");
return 0;
}
编译的时候,提示有以下错误:
1>e:\c++\temp\temp\x0503.cpp(18): error C2601: “GetInfo”: 本地函数定义是非法的
1>e:\c++\temp\temp\x0503.cpp(9): note: 此行有一个“{”没有匹配项
1>已完成生成项目“temp.vcxproj”的操作 - 失败。
========== 生成: 成功 0 个,失败 1 个,最新 0 个,跳过 0 个 ==========
仔细检查了好多遍,还是没有找到问题,后来才发现,GetInfo这个函数不应该定义在main函数中,也就是C++不支持函数的嵌套定义,但是函数的嵌套调用是可以的!
所以正确的代码如下:
#include<iostream>
#include<string>
#include <vector>
using namespace std;
struct conf
{
char itemname[40];
char itemcontent[100];
};
char * GetInfo(vector<conf *> & conflist, const char *pitem)
{
for (auto pos = conflist.begin(); pos != conflist.end(); ++pos)
{
if (_stricmp((*pos)->itemname, pitem) == 0)
return (*pos)->itemcontent;
}
return nullptr;
}
int main()
{
//ServerName = 1区;
//ServerID = 100000;
conf *pconf1 = new conf;
strcpy_s( pconf1->itemname, sizeof(pconf1->itemname), "ServerName");
strcpy_s( pconf1->itemcontent, sizeof(pconf1->itemcontent), "1区");
conf *pconf2 = new conf;
strcpy_s(pconf2->itemname, sizeof(pconf2->itemname), "ServerID");
strcpy_s(pconf2->itemcontent, sizeof(pconf2->itemcontent), "100000");
vector <conf*>conflist;
conflist.push_back(pconf1);
conflist.push_back(pconf2);
char * p_tmp = GetInfo (conflist, "ServerName");
if (p_tmp != nullptr)
{
cout << p_tmp << endl;
}
//我们要释放内存,new 要对应释放,否则会造成内存泄露
vector<conf*>::iterator pos;
for (pos = conflist.begin() ;pos != conflist.end(); ++pos)
{
delete (*pos);//*pos 才是那个指针//必须自己释放
}
conflist.clear();//这个要不要都行,结束时会系统回收
system("pause");
return 0;
}
输出结果为:1区