简体   繁体   中英

C++ Can I use Identifiers in another class?

I am new to C++ so I'm not sure how to do this. Basically I have some identifiers of type CEdit declared in PvUiSampleDlg.h. They are used in PvUiSampleDlg.cpp.

CEdit mIPEdit;
CEdit mMACEdit;
CEdit mManufacturerEdit;
CEdit mModelEdit;
CEdit mNameEdit;

What I have done is created another class called SettingsDlg.cpp and I want to use the same identifiers in this class as well. How do I go about doing this? I am assuming that you have to get the identifiers in the SettingsDlg.h but I am not sure how to do that. I have #include PvUiSample.h in both the SettingsDlg.cpp and SettingsDlg.h. Any help would be appreciated.

It looks like you're looking for the extern keyword.

When you declare your variables put extern infront of them. This lets the compiler/linker know that these variables will be used outside of this file.

//PvUiSampleDlg.h
extern CEdit mIPEdit;
extern CEdit mMACEdit;
extern CEdit mManufacturerEdit;
extern CEdit mModelEdit;
extern CEdit mNameEdit;

Make sure you only initialize your variables in one place.

//PvUiSampleDlg.cpp
#include "PvUiSampleDlg.h"

CEdit mIPEdit(/* your constructor args*/); // You can initialize like this
...
void someFunc(){
    return mIpEdit;  // do something with your variable as you would normally
}

You can initialize the your variable as seen above. Make sure you include the header containing your extern variables otherwise the initialization will treat it like a normal static variable.

Then in any other file including your header, you can use these variables as you would expect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM