c++ - 在 C++ 中使用 const ArrayType 或 ConstArrayType typedef 具有 const 元素的数组

标签 c++ arrays constants typedef

我将定义一些具有固定大小和常量元素的数组。
我尝试使用 typedef,但似乎有些困惑:

typedef int A[4];
typedef const int CA[4];

const A a = { 1, 2, 3, 4 };
CA ca = { 1, 2, 3, 4 };

a[0] = 0;
ca[0] = 0;
a = ca;
ca = a;

所有赋值都会导致上面代码中的语法错误,我认为 a[0] = 0; 在我测试之前应该是合法的。

考虑指针,
结果更容易理解 p[0] = 0;cp = p; 是正确的。

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;

为什么 cv 限定符在指针和数组上表现不同?
是不是因为数组已经是一个const指针,所以编译器进行了一些隐式转换?

附言我在 Visual Studio 2013 上编译了代码。

最佳答案

这两个声明

const A a = { 1, 2, 3, 4 };
CA ca = { 1, 2, 3, 4 };

完全等价并声明常量数组。如果您将运行这个简单的程序(例如使用 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 A ).name() << std::endl;

    return 0;
}

两个输出语句你会得到相同的结果

int const [4]
int const [4]

事实上你可以这样写

#include<iostream>

typedef int A[4];
typedef const A CA;

int main()
{
    std::cout << typeid( CA ).name() << std::endl;
    std::cout << typeid( const A ).name() << std::endl;

    return 0;
}

同样的结果。

至于指针声明符,则语义有细微差别。您可以将 cv 限定符与指针声明符一起使用

ptr-operator:
    * attribute-specifier-seqopt cv-qualifier-seqopt

你可以这样写

typedef const int * const P;

(指向常量数据的常量指针)。

如果你会这样写

typedef int *P;

然后写

typedef const P CP;

CP 将是一个常量指针时。它指向的对象不是常量。只有指针本身是常量,不能改变。即声明

typedef const P CP;

相当于

typedef int * const CP;

不一样

typedef const int *CP;

在最后一个声明中,指针本身不是常量。它是由具有此类型的指针指向的对象将是常量,并且不能使用此指针进行更改。

简而言之,如果你有

typedef int A[4];

然后

const A a = { 1, 2, 3, 4 };

相当于

const int a[4] = { 1, 2, 3, 4 };

如果你有

typedef int *P;

然后

const P p = new int[4]{ 1, 2, 3, 4 };

相当于

int * const p = new int[4]{ 1, 2, 3, 4 };

考虑到如果你有这样的声明

const int *p;

那么你不需要初始化指针,因为它不是常量。

当你有这样的声明时

int * const p = new int;

或者喜欢

const int * const p = new int; 

你应该初始化指针,因为它是一个常量。否则编译器会报错。

关于c++ - 在 C++ 中使用 const ArrayType 或 ConstArrayType typedef 具有 const 元素的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29393414/

相关文章:

c++ - 当将变量声明移动到接近首次使用时,它们是否在 return 语句之后有关系吗?

c++ - std::is_base_of 可能实现的解释

c++ - std::list 中的 pop_back() 返回值?

arrays - Index Range Swift 中的新数组

c - 函数接受 const char * 但我需要向它传递一个 char*

objective-c - 某种外部变量与静态变量之间的区别

c++ - int* 到常量数组

c++ - union 中的字符串、段错误

c - C 中的字符串搜索和替换程序实现

javascript - 将嵌套数组中的数据合并到一个数组中