为什么我的部分代码没有执行

Why is part of my code not executed?

本文关键字:执行 代码 我的部 为什么      更新时间:2023-10-16

我正在使用Visual C++为Cinema 4D编译插件。

    GeDebugOut("-->");
    subroot = NULL;
    head = NULL;
    tail = NULL;
    success = PolygonizeHierarchy(source, hh, head, tail, &subroot, malloc);
    if (!success) {
        /* .. */
    }
    String str("not set.");
    if (subroot) {
        GeDebugOut("yes");
        str = "yes!";
        GeDebugOut("Subroot name: " + subroot->GetName());
    }
    else {
        GeDebugOut("no");
        str = "no!";
    }
    GeDebugOut("Is there a subroot?   " + str);
    GeDebugOut("<--");

预期输出如下:

-->
yes
Subroot name: Cube
Is there a subroot?  yes
<--

(或者用"否"代替。)但我得到了

-->
yes
<--


为什么这里少了两张照片


这是GeDebugOut的声明。

void GeDebugOut(const CHAR* s,  ...);
void GeDebugOut(const String& s);

String类是可连接的。它使+运算符过载。

String(void);
String(const String& cs);
String(const UWORD* s);
String(const CHAR* cstr, STRINGENCODING type = STRINGENCODING_XBIT);
String(LONG count, UWORD fillch);
friend const String operator +(const String& Str1, const String& Str2);
const String& operator +=(const String& Str);

您需要像使用printf:一样使用GeDebugOut

GeDebugOut("Some message =  %s ", whatever);

其中whatever是c字符串,即其类型为char*

由于GeDebugOut的重载也接受String类型,因此我认为您需要使用unicode作为:

GeDebugOut(L"Is there a subroot?   " + str);
        // ^ note this!

因为我怀疑如果启用unicode,那么CHAR基本上是wchar_t,而不是char。因此,字符串串联不起作用,因为字符串文字不会隐式转换为String类型,从而传递给+重载。

不能将字符串附加到字符串文字中。

"Is there a subroot"是一个字符串文字,编译器会将其用作指向该文字的指针。

更好的方法是:

GeDebugOut("Is there a subroot? %s ", str);

如前所述,编译器可以从以下两个版本中选择GeDebugOut

void GeDebugOut(const CHAR* s,  ...);
void GeDebugOut(const String& s);

当它遇到:

GeDebugOut("Is there a subroot?   " + str);

"Is there a subroot"是一个字符串文字,可翻译为类型const char*。我怀疑String具有某种数字类型的转换运算符。所以编译器选择了第一个重载。

这导致了您没有预料到的行为,因为const char*+操作是指针算术,而不是字符串串联,所以您在字符串文字的指针和上调用GeDebugOut,无论strconst char*转换的输出是什么。

有几种方法可以纠正这种情况。正如另一个提到的,您可以将其更改为类似printf的语法。或者你可以强迫它使用String覆盖,就像这样:

GeDebugOut(String("Is there a subroot?") + str);