【问题标题】:Declare const pointer to int?声明指向 int 的 const 指针?
【发布时间】:2011-12-14 00:07:36
【问题描述】:

在 C++ 中,我们有以下内容:

int* p1;              // pointer to int
const int* p2;        // pointer to constant int
int* const p3;        // constant pointer to int
const int* const p4;  // constant pointer to constant int

在 D 中:

int* p1;              // pointer to int
const(int)* p2;       // pointer to constant int
?? ?? ??              // constant pointer to int
const(int*) p4;       // constant pointer to constant int

constant pointer to int 的语法是什么?

【问题讨论】:

    标签: pointers integer constants d


    【解决方案1】:

    【讨论】:

    • 也不是 C++ 风格的 tail-const(在同一页上)。
    【解决方案2】:

    我想你可以模拟一下:

    struct Ptr(T)
    {
        T* _val;
    
        this(T* nval) const
        {
            _val = nval;
        }
    
        @property T* opCall() const
        {
            return cast(T*)_val;
        }
    
        alias opCall this;
    }
    
    void main()
    {
        int x = 1;
        int y = 2;
        const Ptr!int ptrInt = &x;
        assert(*ptrInt == 1);
    
        *ptrInt = y;  // ok
        assert(*ptrInt == 2);
        assert(x == 2);
    
        ptrInt = &y;  // won't compile, good.
    }
    

    【讨论】:

      猜你喜欢
      • 2015-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-10
      • 1970-01-01
      相关资源
      最近更新 更多