ptr::operator bool
在條件運算式中用於 com::ptr 的運算子。
operator bool();
傳回值
如果指定的 COM 物件有效,則為 true,否則為 false。
備註
如果它不是 nullptr,擁有有效的 COM 物件。
比 bool 安全性的這個運算子實際上會轉換成 _detail_class::_safe_bool ,因為它無法轉換為整數型別。
範例
這個範例會使用 com::ptr 包裝其私用成員 IXMLDOMDocument 物件的 CLR 類別。 CreateInstance 成員函式來建立新的資料物件之後決定是否使用 operator bool 有效並寫入主控台。
// comptr_op_bool.cpp
// compile with: /clr /link msxml2.lib
#include <msxml2.h>
#include <msclr\com\ptr.h>
#import <msxml3.dll> raw_interfaces_only
using namespace System;
using namespace System::Runtime::InteropServices;
using namespace msclr;
// a ref class that uses a com::ptr to contain an
// IXMLDOMDocument object
ref class XmlDocument {
public:
void CreateInstance(String^ progid) {
if (!m_ptrDoc) {
m_ptrDoc.CreateInstance(progid);
if (m_ptrDoc) { // uses operator bool
Console::WriteLine("DOM Document created.");
}
}
}
// note that the destructor will call the com::ptr destructor
// and automatically release the reference to the COM object
private:
com::ptr<IXMLDOMDocument> m_ptrDoc;
};
// use the ref class to handle an XML DOM Document object
int main() {
try {
XmlDocument doc;
// create the instance from a progid string
doc.CreateInstance("Msxml2.DOMDocument.3.0");
}
catch (Exception^ e) {
Console::WriteLine(e);
}
}
需求
標頭檔<msclr \ com \ ptr.h>
命名空間 msclr::com