2010-12-20 40 views
1

這樣的事情:(這是任務,如何做到這一點,而不是改變主體功能)如何「重新定義」一個char *爲另一個char *?

我認爲這太簡單了......但是......我不知道如何去做做...

#include <iostream> 

#define "a" "b" 

int main(int argc,char ** argv) { 
    std::cout << "a"; 
    return 0; 
} 

//輸出:乙

怎麼辦呢?

+13

敢問我爲什麼要進行這種不自然的行爲? – 2010-12-20 15:14:40

+0

你不能。你最好使用簡單的if(用於輸入)。不過,我認爲你不能對輸出做任何事情。 – Lockhead 2010-12-20 15:16:23

+2

爲相關性添加了'預處理器'標記。 – Maxpm 2010-12-20 15:17:58

回答

4

Changing C++ output without changing the main() function

例如從該主題:

#include <iostream> 
#include <cstdio> 
#include <sstream> 

#define cout  printf("a"); std::ostringstream os; os 

int main() 
{ 
    std::cout << "b"; 
} 

一個simplier之一:

#include <iostream> 
#define cout cout << "a"; return 0; std::cout 
int main() 
{ 
    std::cout << "b"; 
} 
+0

它不適用於std ::: cout <<「b」; – 2010-12-20 16:14:50

+0

對不起,printf出現了輸入錯誤 – 2010-12-20 16:33:21

+3

隨着時間的推移,我開始相信,在C++中,「不可能」對於任何需要解決的問題來說都只是暫時的答案。在所有情況的80%中,有人會出現並彎曲模板,宏和其中一些我們相互融洽的特徵,而不會達到他們的目的,從而實現每個人都認爲是絕對不可能的。在這個想法之前,我鞠躬,雖然有點不寒而慄。願你活得長久,可能你的代碼永遠不會跨越我的道路。 – sbi 2010-12-27 22:05:47

2

你不能。預處理器不會「查看」字符串文字。

+0

好吧,如果我不能做到這一點如何解決這個問題? – 2010-12-20 15:15:53

+0

@mr。瓦喬夫斯基:什麼問題?代碼可以在不通過預處理器運行的情況下被讀取和理解的「問題」? – delnan 2010-12-20 15:18:17

+0

@mr。這不是一個_problem_,你想做什麼?你總是可以'cout <<「b」;' – Motti 2010-12-20 15:18:50

8

幸運的是,您無法重新定義字符串文字。當然,真正的問題是:爲什麼你要做呢?

+0

我這是作業:) – 2010-12-20 15:37:59

4

宏名稱必須是標識符,因此不能包含字符"

0

也許你想這樣做:

#include <iostream> 

#define a "b" 

int main(int argc,char ** argv) { 
    std::cout << a; 
    return 0; 
} 

輸出:b

+0

很明顯) – 2010-12-25 15:21:05

0

#define是一個不好的c++風格。使用const

#include <iostream> 
// const char * string_a = "a"; // Regular: Use const char * 
const char * string_a = "b"; // Replacing: Instead of bad #define "a" "b" 

int main(int argc,char ** argv) {  
    std::cout << string_a;  
    return 0; 
}