【问题标题】:conversion from const pointer to pointer从 const 指针到指针的转换
【发布时间】:2014-11-25 22:16:35
【问题描述】:

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

我怎么知道当我使用例如“int& num = other”时,我得到了“other”的引用,所以我可以更改其他...所以当我使用“const int& num = other”时,我只能在无法更改内容的情况下查看其他内容。

所以我认为当我使用“const Point*& p = other”时,我实际上拥有 other 的内容(这是 Point 的地址),但在某种程度上我无法更改它。

所以如果以上都是真的,为什么我不能将它发送到接收 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);
}

和带有addPoint函数的Polygon:

#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;
}


}    

谢谢!

【问题讨论】:

  • 为什么要通过引用传递指针?指针不会占用太多空间,因此您应该按值传递它们,因为您没有修改它们。

标签: c++ pointers inheritance


【解决方案1】:

您的 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 变量并将其复制到非 const ?对我来说,拥有一个我不想更改的变量(我从构造函数调用者获得的那个)并将 -- 它的值 -- 粘贴到我将能够修改的其他地方(比如那个在cevtor中)...
  • @doron-BGUbgu 您可以使用 const variable 并将其复制到非 const 变量,但不能复制指向 const 或引用的指针-const 只是一个指针或引用,因为这可能会违反const。问题不在于更改 - 这里的值只是地址,您可以只是 const T* 的地址 - 问题在于更改指针。
  • 因此const Point*Point *const之间的区别。
【解决方案2】:

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

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

【讨论】:

  • 谢谢。那么我怎么能说我想要指向 Point 的 const 指针呢?
  • @doron-BGUbgu Point* const p;
猜你喜欢
  • 2015-09-10
  • 2017-05-15
  • 1970-01-01
  • 1970-01-01
  • 2013-10-20
  • 1970-01-01
  • 2011-02-23
  • 1970-01-01
  • 2013-11-23
相关资源
最近更新 更多