C++ 复制一个常量引用指针

C++ Copying a Const Referenced Pointer

我们在将指针引用作为常量传递、将引用的指针复制到非常量并将其发送到 class 函数时遇到问题。

这个问题有一个简单的解决方法:允许传递的参数作为非常量传递。不幸的是,这是一个项目,头文件必须保持不变。基本思路如下:

因此:

class Point
{
    int dim;          // number of dimensions of the point
    double *values;   // values of the point's dimensions
}

和:

typedef Point * PointPtr;          // Points to a point
typedef struct LNode * LNodePtr;   // Points to a link node

struct LNode         // Link node structure
{
    PointPtr p;      // Points to a point
    LNodePtr next;   // Points to the next link node
};

class Cluster
{
    int size;
    LNodePtr points;

public:
    Cluster &operator+=(const Point &rhs);   // Add a point
}

我们需要重载 += 运算符以将一个点添加到一个簇中,并给出了上述声明。到目前为止,唯一有点行为的代码如下:

Cluster &Cluster::operator+=(const Point &rhs)   // This line is not allowed to change
{
    PointPtr newPtPtr = new Point(rhs);
    this->add(newPtPtr);   // Adds the point to the cluster
    return *this;
}

但是,这会在宇宙中创建一个新的物理点。

我们希望看到的工作大致如下:

Cluster &Cluster::operator+=(const Point &rhs)
{
    PointPtr newPt = &rhs;   // This could also be type "Point *"
    this->add(newPt);
    return *this;
}

但我收到一条 "invalid conversion" 消息:

error: invalid conversion from 'const Clustering::Point*' to 'Clustering::PointPtr {aka Clustering::Point*}' [-fpermissive]
     PointPtr newPt = &rhs;

我所看到的不同之处在于常量 - 是否有任何解决方法来捕获该引用的指针地址?

如果以后实际尝试修改 Point,它会出现未定义的行为,但我认为你可以写

Cluster &Cluster::operator+=(const Point &rhs)
{
    PointPtr newPt = const_cast<PointPtr>(&rhs);
    this->add(newPt);
    return *this;
}