我有一个类,它解析命令行参数,然后将解析后的值返回给客户端类。对于解析,我需要传递argv
给解析函数。我想通过引用传递,但据我所知,我们在传递数组时从不使用“&”符号。数组不是可以通过引用传递的对象。这是我的代码:
#include <iostream>
#include <fstream>
using namespace std;
class cmdline
{
const char * ifile;
public:
cmdline():ifile(NULL){}
const char * const getFile() const
{
return (ifile);
}
void parse(int argc,const char** argv)
{
//parse and assign value to ifile
// ifile = optarg;
// optarg is value got from long_getopt
}
};
int main(int argc, char ** argv)
{
cmdline CmdLineObj;
CmdLineObj.parse(argc, const_cast<const char**>(argv));
const char * const ifile = CmdLineObj.getFile();
ifstream myfile (ifile);
return 0;
}
1)argv
处理的方式对吗?
2)更好的处理方式,ifile
?
3) 我想ifile
作为参考返回,如果需要,我应该做些什么改变?
我的代码按照它应该工作的方式工作,但我来到 SO 的原因是“不仅仅是让它工作”,而是要正确地做到这一点。
谢谢你的帮助。
编辑:: 在 Mehrdad 发表评论后,我编辑如下:
class CmdLine
{
const char * ifile;
public:
const char * & getFile() const
{
return (ifile);
}
但是我得到了错误-从类型'const char'的表达式中对类型'const char *&'的引用的无效初始化</p>