声明const指针指向int?

时间:2011-12-14 00:07:37

标签: pointers integer const d

在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的语法是什么?

2 个答案:

答案 0 :(得分:10)

答案 1 :(得分:5)

我认为你可以模拟它:

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.
}