c++ - const、指针、typedef 和星号

标签 c++ pointers constants typedef

Possible Duplicate:
what is the difference between const int*, const int * const, int const *

大家好,

我想知道当指针涉及以下方面时,是否有人可以对 typedef 的语法提供一些清晰的说明: - 星星位置的含义; - const 位置的含义; - 两者之间的互动。

在编写下面的示例后,我对 const 和 star 发生了什么有了了解,但我只是通过反复试验获得了该代码,并且希望从知识渊博的人那里获得更多理论解释。

谢谢

#include <iostream>
using namespace std;

int main() {
    int paolo = 10;

    // POINTERS
    typedef int* PointerToInt1;
    typedef int *PointerToInt2;

    // POINTERS TO CONST
    typedef const int* PointerToConstInt1;
    typedef const int *PointerToConstInt2;
    typedef int const* PointerToConstInt3;
    typedef int const *PointerToConstInt4;
    // qualifying with const twice
    // ignored -  simply gets you a warning
    typedef const int const* PointerToConstInt5;
    typedef const int const *PointerToConstInt6;

    // CONST POINTERS
    typedef int *const ConstPointerInt1;
    typedef int* const ConstPointerInt2;

    // CONST POINTERS TO CONST
    typedef const int *const ConstPointerToConstInt1;

    //  POINTERS
    int *ip1 = &paolo;
    int* ip2 = &paolo;
    PointerToInt1 ip3 = &paolo;
    PointerToInt2 ip4 = &paolo;

    // POINTERS TO CONST
    PointerToConstInt1 ip11;
    PointerToConstInt2 ip12 = &paolo;
    PointerToConstInt3 ip13;
    PointerToConstInt4 ip14 = &paolo;
    PointerToConstInt3 ip15;
    PointerToConstInt4 ip16 = &paolo;

    /*
    //  POINTERS TO CONST 
    //ALL ERROR
    *ip11 = 21;     *ip12 = 23;
    *ip13 = 23;     *ip14 = 23;
    *ip15 = 25;     *ip16 = 23;
    */

    // CONST POINTERS
    // ERROR - No initialiser
    // ConstPointerInt1 ip21;    
    // ConstPointerInt2 ip22;
    int me = 56;
    int you = 56;
    ConstPointerInt1 ip21 = &me;    
    ConstPointerInt1 ip22 = &me;    
    *ip21 = 145;
    *ip22 = 145;

    // ERROR - No initialiser
    // ConstPointerToConstInt1 ip31;

    // ERROR - Cant change  eobjected pointed at 
    ConstPointerToConstInt1 ip31 = &me;
    // ip31 = &you;

    // ERROR - Cant change  the value of objected pointed at 
    ConstPointerToConstInt1 ip33 = &me;
    // *ip31 = 54;


    cout << *ip1 << *ip2 <<  *ip4 <<   endl;
    cout << *ip11 <<  *ip12 << *ip13 << *ip14 << *ip15 <<  *ip16 << endl; 


    return 1;

}

最佳答案

有关使用 const 的一般规则,StackOverflow 上有数十亿个问题。例如:const usage with pointers in C .

关于 typedef,编写 typedef 的规则与编写变量声明的规则相同;唯一的区别是你在它前面添加了 typedef 前缀,并将变量的名称替换为 typedef 的名称! (除了少数异常(exception),通常用括号固定)。因此,例如:

char *flaps;

变成:

typedef char *flaps_type;

关于c++ - const、指针、typedef 和星号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5598121/

相关文章:

对将字符传递给函数参数时何时使用 int 类型或 char 类型感到困惑?

c - 在 C 中#ifdef 中定义常量

c++ - 使用线程处理信号和槽

c++ - C 中存在大量空变量,总大小超过内存

c++ - 如何在 C++ 函数中正确使用指针?

c - 如何用指针在c中添加相邻的数组项?

c++ - SFINAE 显式工作但不隐式工作

c++ - Cmake 生成独立的makefile

c++ - 同一地址的变量如何产生 2 个不同的值?

c - 多个 const 限定符是什么意思?