[英]C++ Passing C-style string as argument
I'm having some trouble dealing with C-style strings in c++. 我在处理C ++中的C样式字符串时遇到一些麻烦。 In short what I'm trying to do is pass a cstring from my main method into the constructors of one of my objects. 简而言之,我想做的就是将cstring从我的main方法传递到我的一个对象的构造函数中。
For example 例如
class sample
{
public: // Initalization
Sample( const char * inFile);
}//End sample class
Then in the main method. 然后在主要方法。
//Main method
int main ( int argc, const char * argv[] )
{
Sample aSample(argv[1]);
}
Now, based on my assumption I should be getting back a const char*
when I dereference the second pointer using argv[1]
. 现在,基于我的假设,当我使用argv[1]
取消引用第二个指针时,我应该返回一个const char*
。 From my understanding char *argv[]
is just another way of saying char **argv
. 以我的理解, char *argv[]
只是char **argv
另一种说法。
Also, just to make sure my understanding of const is correct, const char *
is saying "this pointer points to a const char" where const char const *
is saying " this pointer address can not be changed, and the address it points to is const as well". 另外,为了确保我对const的理解是正确的, const char *
说“此指针指向const char”,而const char const *
说“此指针地址不能更改,并且它指向的地址是” const”。
Update - 更新-
Just to clarify this is a two part question. 只是为了澄清这是一个两部分的问题。
Updated my incorrect statement above that i dereferenced the "first" pointer when it should have been the "second". 更新了我上面的错误陈述,即当它应该是“第二”指针时,我取消了对“第一”指针的引用。 Thank you below for pointing that out. 下面感谢您指出这一点。
2nd update - I'm using argv[1] because I'm receiving information from the command line and argv[0] holds only the path of the executable, which I'm not interested in. 第二次更新-我正在使用argv [1],因为我从命令行接收信息,而argv [0]仅保存可执行文件的路径,对此我不感兴趣。
Any help is greatly appreciated. 任何帮助是极大的赞赏。
-Freddy -弗雷迪
argv[1]
dereferences the second pointer, not the first. argv[1]
取消引用第二个指针,而不是第一个。 You want argv[0]
. 您需要argv[0]
。 Arrays in C++ are 0-based . C ++中的数组基于0 。
Also: 也:
const char const *
isn't legal (credits to Benjamin for pointing it out). 是不合法的(本杰明指出了这一点)。 Both const
s are applied to the char
in this case. 在这种情况下,两个const
都应用于char
。 If you want the pointer to be const, you need 如果要使指针为const,则需要
char const * const
or 要么
const char * const
EDIT: 编辑:
Question 1) A CString can take a char*
as parameter for the constructor, so it should work. 问题1)CString可以将char*
作为构造函数的参数,因此它应该可以工作。
Question 2) const
binds to the left, unless there's nothing to the left. 问题2) const
绑定到左边,除非左边什么都没有。 So const char
and char const
are the same. 因此const char
和char const
是相同的。 For a const pointer, you need * const
, not const *
. 对于const指针,您需要* const
,而不是const *
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.