gpt4 book ai didi

c++ - 如何在 C++ 中将命令行参数的整个集合(char**)作为只读传递?

转载 作者:可可西里 更新时间:2023-11-01 18:27:48 26 4
gpt4 key购买 nike

假设我有这样一个程序:

#include <iostream>
#include <string>
#include <vector>

// Takes values and outputs a string vector.
std::vector<std::string> foo(const int argc, char* args[]) {
std::vector<std::string> strings;
for (int i = 0; i < argc; i++)
strings.push_back(args[i]);
return strings;
}

int main(int argc, char *args[]) {

std::vector<std::string> strings = foo(argc, args);

for (unsigned int i = 0; i < strings.size(); i++)
std::cout << strings[i] << std::endl;

return 0;
}

要点是我正在尝试将 main() 函数的 char** 参数传递给另一个函数或类。 (我知道有更好的方法可以实现上述程序的功能,我的问题是关于将 char** 参数作为只读传递)。

问题:

  1. 我发现我不能像第一个那样使第二个 foo() 参数为常量。为什么是这样? char** 无法转换为 const char**?
  2. 我想将此参数作为“只读”传递。我不确定该怎么做,如果它是一个字符串,我会通过 const 引用传递它,但我不确定如何使用指针来处理它?<​​/li>

最佳答案

I've found that I can't make the second foo() argument const like the first. Why is this? A char** can't be converted to a const char**?

如果允许,您很可能会破坏 const 的正确性。考虑一下

char const *a = "literl";
char *b = nullptr;
char const **c = &b; // This is not allowed in C++. Like your code.
*c = a; // The qualifications match, but now it's b that points at a literal.
*b = 'L'; // Modifying a string literal! Oops!

因此有充分的理由按书面形式禁止它。但这并不意味着你根本不能做你想做的事。只要更严格,资格转换是可能的。好吧,这就是它的要点。

I want to pass in this argument as "read-only". I'm not sure how to go about this, if it were say a string I'd pass it in via const reference, but I'm not sure how to go about this with pointers?

将指向 const 的指针传递给 const char。最好写成代码来解释:

                                                         // The const here
std::vector<std::string> foo(int const argc, char const* const args[]) {
std::vector<std::string> strings;
for (int i = 0; i < argc; i++)
strings.push_back(args[i]);
return strings;
}

为什么允许这样做?因为如果我们把它等同于我开始时的坏例子,c 不能再被用来赋值给 b,所以我们就不会进入错误状态。

关于c++ - 如何在 C++ 中将命令行参数的整个集合(char**)作为只读传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54629440/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com