从常量指针到指针的转换

conversion from const pointer to pointer

本文关键字:指针 转换 常量      更新时间:2023-10-16

我正在尝试将矩形构造函数 ref 传递给 const Point*,以便我可以将实际的 Point* 添加到 addPoint 函数(将经过她的代码)。

好吧,我怎么知道,当我使用例如"int&num = other"时,我会将 ref 转换为"其他",以便我可以更改其他...因此,当我使用"const int&num = other"时,我只能看到 OTHER 内部的内容,而无法更改其内容。

所以我想当我使用"const Point*&p = other"时,我通常拥有 other 的内容(这是 Point 的地址),但在某种程度上我无法更改它。

因此,如果以上所有内容都是真的,为什么我不能将其发送到接收点*的addPoint? 据我了解,编译器将从"p1"复制地址,这是 Point 的地址,并将其粘贴到矢量中新插槽中的新 Point* 中。这不就是哈帕内斯吗?

我得到的任何方式:

invalid conversion from ‘const Point*’ to ‘Point*’ [-fpermissive]

这是我的代码(矩形是多边形固有的)

Rectangle::Rectangle(const int& color, const Point*& p1, const Point*& p2, const Point*& p3, const Point*& p4) : Polygon(color, "Rectangle")
{
    addPoint(p1);
    addPoint(p2);
    addPoint(p3);
    addPoint(p4);
}

和具有添加点功能的多边形:

#include "Point.h"
#include "Polygon.h"
#include <iostream>
#include <cstdlib>
using std::cout;
using std::endl;
using std::vector;

Polygon::Polygon() : _points(), _color(0), _type("")
{}
Polygon::~Polygon() {
    clear();
}
Polygon::Polygon(const Polygon& other) : _points(), _color(other._color), _type(other._type)
{
    getDataFrom(other);
}

Polygon::Polygon(const int& color, const string& type) : _points(), _color(color) , _type(type)
{
}

void Polygon::addPoint(Point* p) {
    Point* newp = new Point; //create a copy of the original pt
    newp->setX(p->getX());
    newp->setY(p->getY());
    _points.push_back(newp);
}
void Polygon::clear()
{
    vector<Point*>::iterator iter = _points.begin();
    cout << "DELETING POLYGON: BEGIN" << endl;
    while (iter != _points.end()) {
        delete (*iter);
        iter++;
    }
    cout << "DELETING POLYGON: END" << endl;
}

}    

谢谢!

您的addPoint()采用非常量指针:

void Polygon::addPoint(Point* p) {

但是您正在尝试传递它const Point*,因此出现错误。编译器不知道你最终没有修改p指向的内容 - 所以让你做你想做的事情可能违反了const

例如,如果addPoint()这样做:

void Polygon::addPoint(Point* p) { p->setX(42); }

让你通过const Point*显然是错误的。

但是,由于您实际上不需要p指向非常量Point因此您只需更改签名即可反射以下内容:

void Polygon::addPoint(const Point* p) {

const Point*的意思是"指向const Point的指针",换句话说,指针指向的对象是常量。不能将其分配给类型为 Point* 的变量(这意味着"指向非常量Point的指针"),因为它将允许您修改基础Point对象。

如果你想要一个指向非常量Point的常量指针,请将其声明为 Point* const