2

我一直在使用 OpenCV,我看到的一些示例代码使用以下内容来读取文件名。我知道 argc 是传递的命令行参数的数量,而 argv 是参数字符串的向量,但是有人可以澄清以下行的每个部分的作用吗?我试过搜索这个,但没有找到很多结果。谢谢。

const char* imagename = argc > 1 ? argv[1] : "lena.jpg";

谢谢。

4

4 回答 4

6
const char* imagename =  // assign the string to the variable 'image_name'
       argc > 1          // if there is more than one cmd line argument (the first is always the program name)
       ? argv[1]         // use the first argument after the program name
       : "lena.jpg";     // otherwise use the default name of "lena.jpg"
于 2010-06-30T17:16:00.940 回答
2

如果 argc 大于 1,则将保存的指针分配给 imagename argv[1](即命令行中给出的第一个参数);否则(argc 不大于 1),分配默认值“lena.jpg”。

它使用三元运算符?:。这是这样使用的:CONDITION ? A : B并且可以读作

if (CONDITION)
  A
else
  B

因此,如果为真,则将a = C ? A : BA分配给 ,否则分配给。在这种特定情况下,“A”和“B”是指向( ) 的指针;该属性表示我们有“常量”的“字符串”。aCBacharchar *const

于 2010-06-30T17:15:49.020 回答
1
if (argc > 1) {
  const char* imagename = argv[1];
} else {
  const char* imagename = "lena.jpg";
}

(如果我们同意imagename可以超出括号的范围)

于 2010-06-30T17:16:45.130 回答
1

该示例显示了三元运算符的使用。

const char* imagename = argc > 1 : argv[1] : "lana.jpg" 通过三元,你可以说这个表达式有三个成员。

第一个成员是条件表达式

如果条件表达式为真,第二个成员是可以分配给 imagename 的值。

第三个成员是如果条件表达式为 false 时可以分配给 imagename 的值。

这个例子可以翻译成:

const char* imagename;
if(argc > 1)
    imagename = argv[1];
else
    imagename = "lana.jpg";
于 2010-06-30T17:29:50.427 回答