2012-07-25 90 views
5

我正在使用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); 
+0

如何聲明'GeDebugOut'? – jxh 2012-07-25 15:41:36

+0

@ user315052看我的編輯,請見。 – 2012-07-25 15:45:36

+1

是'字符串'的'std :: string' typedef? – jxh 2012-07-25 15:46:54

回答

5

你需要一個像你使用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類型,將傳遞給+過載。

+0

哦,很高興知道。但現在應用程序崩潰,我猜是因爲它期望'char *'並且我傳遞了String。但是'String'類可以連接,所以爲什麼它不能這樣工作呢? – 2012-07-25 15:44:50

+0

另請參閱我的編輯,其中包括'GeDebugOut'的聲明 – 2012-07-25 15:46:00

+0

@NiklasR:'whatever'應該是一個c-string。 – Nawaz 2012-07-25 15:46:21

1

您不能將字符串附加到字符串文字。

"Is there a subroot"是一個字符串文字,編譯器會看到它的使用作爲指向該文字的指針。

一個更好的辦法是做:

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

正如你提到的,也有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,不管那輸出const char*str的轉換是。

有幾種方法可以解決這個問題。另外提到,您可以將其更改爲類似printf的語法。或者你可以強迫它使用像String這樣的覆蓋:

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

糾正後編輯注意到編譯器不允許在指針變量之間進行算術運算,儘管'String'不太可能轉換爲數字類型,所以我的懷疑似乎不太有效。 – JohnMcG 2012-07-25 16:12:08

相關問題