简单来说,const pointer 是top-level const,pointer to const是low-level const。从人的眼睛出发,我们是先看到pointer(top level),再看到pointer指向的对象(low level),层层剥开,高屋建瓴。对于 reference中的const语义来说,都是low-level的。 关于拷贝对象,我们来举个例子: int gemfield = 7030; int* const p...
// const_pointer2.cppstructX{X(inti) : m_i(i) { }intm_i; };intmain(){// correctconstXcx(10);constX * pcx = &cx;constX ** ppcx = &pcx;// also correctXconstcx2(20); Xconst* pcx2 = &cx2; Xconst** ppcx2 = &pcx2; } ...
};voidChangeSize(constVar *aa){ ///< aa is a pointer to a const, aa itself can be changed, but var it pointed can not be changed. aa->setSize(89); ///< equal as setSize(const Var *this, const int &size) {d_size = size}, now that aa is a pointer to a const this poi...
代码语言:cpp 复制 classMyClass{public:staticconstint*myStaticConstPointer;};constint*MyClass::myStaticConstPointer=nullptr; 在这个示例中,我们定义了一个名为MyClass的类,其中包含一个名为myStaticConstPointer的静态const指针。然后,我们在类定义之外初始化该指针,将其设置为nullptr。 在实际应用中,您可能需要...
// ok: pV is an interior pointer interior_ptr<int const> pn3 = &n; // *pn3 = 5; error because pn3 cannot be dereferenced and changed pn3 = &o; // OK, can change the memory location interior_ptr<int> const pn4 = &n; *pn4 = 5...
// std_tr1__unordered_map__unordered_multimap_const_pointer.cpp // compile with: /EHsc #include <unordered_map> #include <iostream> typedef std::unordered_multimap<char, int> Mymap; int main() { Mymap c1; c1.insert(Mymap::value_type('a', 1)); c1.insert(Mymap::value_type('b...
constdouble*cptr = π// ok: cptr is a pointer to const constvoid*cpv = π// ok: cpv is const doubledval = 3.14; cptr = &dval;// ok: but can't change dval through cptr 可以通过赋值改变指针本身的值,但不能通过指针(eg:*p)改变指针指向的值。
// basic_string_const_ptr.cpp // compile with: /EHsc #include <string> #include <iostream> int main( ) { using namespace std; basic_string<char>::const_pointer pstr1a = "In Here"; const char *cstr1c = "Out There"; cout << "The string pstr1a is: " << pstr1a << "." <...
常量指针:指向“常量”的指针 即 “a pointer to const” 常量指针:指向const 变量的指针(const T*/T const*) const 常量只能用const指针,非const常量可以用const指针也可以用非const指针。 可以改变他的指向对象。 可以不初始化。 不能对*p进行操作。
int main() { int x { 5 }; int* ptr { &x }; // ptr is a normal (non-const) pointer int y { 6 }; ptr = &y; // we can point at another value *ptr = 7; // we can change the value at the address being held return 0; } Copy With normal (non-const) pointers, we ...