假设我有一个这样的程序:
e.g. Input: Internal representation
5 3 NOTHING TO DO
1 2 100 [1 2 value 100]
2 5 100 [1 1 value 100][2 2 value 200(100+100)][3 5 value 100]
3 4 100 [1 1 value 100][2 2 value 200(100+100)][3 4 value 200(100+100)][5 5 value 100]
as an optimization you could merge intervals with same value
-> [1 1 value 100][2 4 value 200][5 5 value 100]
最重要的是,我正在尝试将main()函数的char **参数传递给另一个函数或类。 (我了解实现上述程序的更好方法,我的问题是将char **参数传递为只读)。
问题:
答案 0 :(得分:9)
我发现我不能像第一个一样使第二个foo()参数成为const。为什么是这样?不能将char **转换为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!
因此,有充分的理由不按书面要求使用它。但这并不意味着您根本无法做自己想做的事情。只要更严格,就可以进行资格转换。嗯,这就是要点。
我想以“只读”形式传递此参数。我不确定该如何处理,如果说要通过const引用将其传递给一个字符串,但我不确定如何使用指针进行处理?
将指向 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
,因此我们不会陷入错误的状态。