防范式编程
C++头文件写法
test.h
#ifndef __TEST__
#define __TEST__
int i = 100;
…
#endif
main.cpp
#include “stdafx.h”
#include “test.h”
#include “test.h”
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
C++写法
test.h
#pragma once
int i = 100;
main.cpp第二次#include “test.h”的时候发现__TEST__已经被定义了,所以不会执行下面代码。
如果不进行防范式编程,代码会报如下error:
error C2374: ‘i’ : redefinition; multiple initialization
本文介绍了C++中如何使用防范式编程避免重复包含头文件导致的变量多重定义问题。通过对比传统的ifndef/define方法和#pragma once指令,展示了两种方法的工作原理及优缺点。
478

被折叠的 条评论
为什么被折叠?



