【发布时间】:2011-09-18 04:45:05
【问题描述】:
我有一个类可以解析命令行参数,然后将解析后的值返回给客户端类。对于解析,我需要传递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*&”类型的引用进行无效初始化
【问题讨论】:
-
“我的代码按其应有的方式工作”是什么意思?这段代码甚至无法编译。
-
@Mankrase,我已经编辑了代码。它现在编译得很好。感谢您指出。你觉得这段代码有什么问题吗(我的意思是一些未定义的行为或我绝对应该注意的事情?我真的想通过引用返回 ifile)
-
@Ian:
const char * const getFile() const毫无意义。第二个const应该做什么? -
@Mehrdad ,不应该是指向 const char * 的 const 指针吗?如果不需要,我可以将其删除。感谢您的输入。知道如何返回 ifile 作为参考吗?
-
@Ian: 将“const 指针”返回给某物没有任何意义,因为它的行为与 不是 'const' 的指针没有什么不同(因为它是返回方法的类型,通常不能分配给返回值)。至于通过引用返回ifile:为什么不直接返回
const char *&?
标签: c++ unix multidimensional-array reference argv