2015-11-27 21 views
-3

我可以使用類成員變量作爲全局嗎?如何將變量用作全局變量?

我想使用類的成員變量作爲全球類似以下。

// mfc_test5Dlg.h : header file 
// 

#pragma once 
#include "afxcmn.h" 
#include "Testview.h" 
#include "atltypes.h" 

Image m_image;<------------------HERE!!! 
Image m_blurgray;<------------------HERE!!! 


// Cmfc_test5Dlg dialog 
class Cmfc_test5Dlg : public CDialogEx 
{ 
... 

// Testview.cpp : implementation file 
// 

#include "stdafx.h" 
#include "mfc_test5.h" 
#include "mfc_test5Dlg.h" 

extern char * fileposition; 
extern int slider_val; 

// CTestview 
CTestview *global_TestView; 

IMPLEMENT_DYNCREATE(CTestview, CScrollView) 

    CTestview::CTestview() 
{ 
    global_TestView = this; 
} 

CTestview::~CTestview() 
{ 
} 


BEGIN_MESSAGE_MAP(CTestview, CScrollView) 
END_MESSAGE_MAP() 


// CTestview drawing 

void CTestview::OnInitialUpdate() 
{ 
    CScrollView::OnInitialUpdate(); 

    CSize sizeTotal; 
    // TODO: calculate the total size of this view 
    sizeTotal.cx = sizeTotal.cy = 100; 
    SetScrollSizes(MM_TEXT, sizeTotal); 


} 

void CTestview::OnDraw(CDC* pDC) 
{ 
    CDocument* pDoc = GetDocument(); 
    // TODO: add draw code here 

     CRect rcWin; 
GetWindowRect(&rcWin); 
int ff; 
ff=rcWin.Width(); 
rcWin.Height(); 

m_image.read("file"); <------------------HERE!!! 
    DoDisplayImage(); 

不過,我已經得到了一些錯誤如下。

------ Build started: Project: mfc_test5, Configuration: Release Win32 ------ 

InitializeBuildStatus: 
    Touching "Release\mfc_test5.unsuccessfulbuild". 
ClCompile: 
    All outputs are up-to-date. 
    All outputs are up-to-date. 
    All outputs are up-to-date. 
ResourceCompile: 
    All outputs are up-to-date. 
mfc_test5Dlg.obj : error LNK2005: "class Magick::Image m_image" ([email protected]@[email protected]@@A) already defined in mfc_test5.obj 
mfc_test5Dlg.obj : error LNK2005: "class Magick::Image m_blurgray" ([email protected]@[email protected]@@A) already defined in mfc_test5.obj 
Testview.obj : error LNK2005: "class Magick::Image m_image" ([email protected]@[email protected]@@A) already defined in mfc_test5.obj 
Testview.obj : error LNK2005: "class Magick::Image m_blurgray" ([email protected]@[email protected]@@A) already defined in mfc_test5.obj 
C:\work\mfc_test5\mfc_test5\Release\mfc_test5.exe : fatal error LNK1169: one or more multiply defined symbols found 

Build FAILED. 

Time Elapsed 00:00:01.94 
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== 

正如你可以看到上面的代碼,我想使用m_image作爲全局類成員變量。

我該如何解決這個問題?

+6

爲什麼你調用變量類成員時,他們顯然不是你的班級成員? –

+0

也許你想要靜態成員變量而不是全局? –

+0

@TommyA有問題嗎? – cabot

回答

0

使用extern關鍵字聲明您在頭變量

extern Image m_image; 
extern Image m_blurgray; 

在一個.cpp(源)文件中定義這些變量。

Image m_image; 
Image m_blurgray; 
+0

明白了,那麼我可以在全局中使用上面的變量嗎?如果我想在另一個cpp中使用相同的變量,這是可能的方式嗎? – cabot

+0

@cabot是的,因爲這些變量將* *全局變量。 –

+0

謝謝大家 – cabot