typedef an array with const elements using const ArrayType or ConstArrayType in c++ -
i going define arrays fixed size , const elements.
tried use typedef, there seems confused:
typedef int a[4]; typedef const int ca[4]; const a = { 1, 2, 3, 4 }; ca ca = { 1, 2, 3, 4 }; a[0] = 0; ca[0] = 0; = ca; ca = a; all assignments cause syntax error in code above think a[0] = 0; should legal before test.
considering pointers,
result easier understand p[0] = 0; , cp = p; correct.
typedef int *p; typedef const int *cp; const p p = new int[4]{ 1, 2, 3, 4 }; cp cp = new int[4]{ 1, 2, 3, 4 }; p[0] = 0; cp[0] = 0; p = cp; cp = p; why cv-qualifier behave different on pointer , array?
because array has been const pointer, compiler makes implicit conversion?
p.s. compiled code on visual studio 2013.
these 2 declarations
const a = { 1, 2, 3, 4 }; ca ca = { 1, 2, 3, 4 }; are equivalent , declare constant arrays. if run simple program (for example using ms vc++)
#include<iostream> typedef const int ca[4]; typedef int a[4]; int main() { std::cout << typeid( ca ).name() << std::endl; std::cout << typeid( const ).name() << std::endl; return 0; } you same result both output statements
int const [4] int const [4] in fact write instead
#include<iostream> typedef int a[4]; typedef const ca; int main() { std::cout << typeid( ca ).name() << std::endl; std::cout << typeid( const ).name() << std::endl; return 0; } with same result.
as pointer declarators semantic has minor difference. may use cv-qualifiers pointer declarators
ptr-operator: * attribute-specifier-seqopt cv-qualifier-seqopt that may write example
typedef const int * const p; (constant pointer points constant data).
thus if write
typedef int *p; and write
typedef const p cp; when cp constant pointer. object points not constant. pointer constant , may not changed. declaration
typedef const p cp; is equivalent to
typedef int * const cp; it not same as
typedef const int *cp; where in last declaration pointer not constant. object pointed pointer having type constant , may not changed using pointer.
shortly speaking if have
typedef int a[4]; then
const a = { 1, 2, 3, 4 }; is equivalent to
const int a[4] = { 1, 2, 3, 4 }; if have
typedef int *p; then
const p p = new int[4]{ 1, 2, 3, 4 }; is equivalent to
int * const p = new int[4]{ 1, 2, 3, 4 }; take account if have declaration like
const int *p; then need not initialize pointer because not constant.
while when have declaration like
int * const p = new int; or like
const int * const p = new int; you shall initialize pointer because constant. otherwise compiler issue error.
Comments
Post a Comment