作者dove1706 (嵐)
看板C_and_CPP
標題Re: [問題] 全域變數宣告在哪?
時間Sun May 10 16:27:34 2009
野人獻曝一下 :) 如我之前略提,CLR我沒碰也不想碰,問題是否出在那裡就不評論了..
下面三個檔案分別存成main.cpp, header1.hpp, header2.hpp, 希望這有幫助
//main.cpp
#include "header1.hpp"
#include "header2.hpp"
#include <iostream>
using namespace std;
int a; // global a, initialized as 0
int main()
{
cout << "a = " << a << "\n";
cla1 c1;
c1.touch_a();
cout << "a = " << a << "\n";
cla2 c2;
c2.touch_a();
cout << "a = " << a << "\n";
}
// EOF of main.cpp
//header1.hpp
extern int a;
class cla1 {
public:
void touch_a() {
a = 1;
}
};
// EOF of header1.hpp
//header2.hpp
extern int a;
class cla2 {
public:
void touch_a() {
a = 2;
}
};
//EOF of header2.hppC
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 91.92.165.253
1F:→ james732:其實我覺得在OO Language裡 應該可以盡量少用全域變數 05/10 17:00
2F:推 tstanly:我也不想碰CLR.....無奈 05/10 17:32
3F:推 tstanly:如果要共用array..上面的方法應該都可吧 05/10 17:38
4F:→ dove1706:同意一樓 用全域的話個人想法是會考慮singleton+mutex 05/11 02:14
※ 編輯: dove1706 來自: 91.92.165.253 (05/17 07:31)