Loading AI tools
来自维基百科,自由的百科全书
在程序設計中,不透明指針(Opaque pointer)是不透明數據類型的一種特殊情況,這種資料類型被聲明為指向某種未指定類型的記錄或資料結構的指針。不透明指針存在於艾達、C語言、C++、D語言和Modula-2 等多種程式語言中
不透明指針是一種向普通客戶端隱藏接口實現細節的方法。這對程式設計師也有好處,因為可以創建一個簡單的接口,而大多數細節可以隱藏在另一個文件中[1]。
package Library_Interface is
type Handle is limited private;
-- Operations...
private
type Hidden_Implementation; -- Defined in the package body
type Handle is access Hidden_Implementation;
end Library_Interface;
package body Library_Interface is
type Hidden_Implementation is record
... -- The actual implementation can be anything
end record;
-- Definition of the operations...
end Library_Interface;
/* obj.h */
struct obj;
/*
* The compiler considers struct obj an incomplete type. Incomplete types
* can be used in declarations.
*/
size_t obj_size(void);
void obj_setid(struct obj *, int);
int obj_getid(struct obj *);
/* obj.c */
#include "obj.h"
struct obj {
int id;
};
/*
* The caller will handle allocation.
* Provide the required information only
*/
size_t obj_size(void) {
return sizeof(struct obj);
}
void obj_setid(struct obj *o, int i) {
o->id = i;
}
int obj_getid(struct obj *o) {
return o->id;
}
/* PublicClass.h */
#include <memory>
class PublicClass {
public:
PublicClass(); // Constructor
PublicClass(const PublicClass&); // Copy constructor
PublicClass(PublicClass&&); // Move constructor
PublicClass& operator=(const PublicClass&); // Copy assignment operator
PublicClass& operator=(PublicClass&&); // Move assignment operator
~PublicClass(); // Destructor
// Other operations...
private:
struct CheshireCat; // Not defined here
std::unique_ptr<CheshireCat> d_ptr_; // Opaque pointer
};
/* PublicClass.cpp */
#include "PublicClass.h"
struct PublicClass::CheshireCat {
int a;
int b;
};
PublicClass::PublicClass()
: d_ptr_(std::make_unique<CheshireCat>()) {
// Do nothing.
}
PublicClass::PublicClass(const PublicClass& other)
: d_ptr_(std::make_unique<CheshireCat>(*other.d_ptr_)) {
// Do nothing.
}
PublicClass::PublicClass(PublicClass&& other) = default;
PublicClass& PublicClass::operator=(const PublicClass &other) {
*d_ptr_ = *other.d_ptr_;
return *this;
}
PublicClass& PublicClass::operator=(PublicClass&&) = default;
PublicClass::~PublicClass() = default;
Seamless Wikipedia browsing. On steroids.
Every time you click a link to Wikipedia, Wiktionary or Wikiquote in your browser's search results, it will show the modern Wikiwand interface.
Wikiwand extension is a five stars, simple, with minimum permission required to keep your browsing private, safe and transparent.