日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

小心使用宏

發布時間:2023/12/9 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 小心使用宏 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

開發過程中,會經常使用宏定義,偶爾還會碰到重復定義的宏,有些時候會造成不良影響。

見如下例子:

Test.h

#ifndef GUARD_TEST_H #define GUARD_TEST_H class CTest { public: CTest(); virtual ~CTest(); void Display(void); public: int x; #ifdef USE_BIG_ARRAY // 注意這里 #pragma message("CTest use big") char szArray[8]; #else #pragma message("CTest use small") char szArray[4]; #endif int y; }; #endif // end of GUARD_TEST_H

Test.cpp

#include "Test.h" #include <memory.h> #include <stdio.h> CTest::CTest() { x = y = 0; memset(szArray, 0, sizeof(szArray)); } CTest::~CTest() { } void CTest::Display(void) { printf("x = %d, y = %d\n", x, y); printf("array is %s\n", szArray); }

TestEx.h

#ifndef GUARD_TESTEX_H #define GUARD_TESTEX_H #define USE_BIG_ARRAY // 注意這里 class CTestEx { public: CTestEx(); virtual ~CTestEx(); void Display(void); public: int x; #ifdef USE_BIG_ARRAY // 注意這里 #pragma message("CTestEx use big") char szArray[8]; #else #pragma message("CTestEx use small") char szArray[4]; #endif int y; int z; }; #endif // end of GUARD_TESTEX_H

TestEx.cpp

#include "TestEx.h" #include <memory.h> #include <stdio.h> // // Construction/Destruction // CTestEx::CTestEx() { x = y = z = 0; memset(szArray, 0, sizeof(szArray)); } CTestEx::~CTestEx() { } void CTestEx::Display(void) { printf("x = %d, y = %d, z = %d\n", x, y, z); printf("array is %s\n", szArray); }

main.cpp

#include <stdio.h> #include <stdlib.h> #include <string.h> #include "./TestEx.h" // 注意這里 #include "./Test.h" // 注意這里 #define USE_BIG_ARRAY int main() { printf("Hello C++\n"); CTest test; test.Display(); putchar('\n'); test.x = 5; strcpy(test.szArray, "Hello"); test.y = 0; test.Display(); return 0; }

運行結果如下:

顯然,這里的y值不是我們想要的


在編譯的時候,編譯器會有如下提示:

Compiling...
main.cpp
CTestEx use big
CTest use big
Test.cpp
CTest use small
TestEx.cpp
CTestEx use big
Linking..


發現,在兩個不同的編譯單元main.cpp 和 Test.cpp里,szArray的定義是不同的。

這就導致在main里,編譯器認為szArray是8個字節的,在Test里,編譯器認為szArray是4個字節的,這樣在進行操作的時候,

就造成的混亂,就造成了上面的結果

提示:慎用宏定義,尤其是在不同的文件里盡量使用不同的宏定義作為判斷條件

實驗代碼:http://download.csdn.net/source/3044231

轉載于:https://www.cnblogs.com/xkxjy/archive/2011/02/26/2078097.html

總結

以上是生活随笔為你收集整理的小心使用宏的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。