【发布时间】: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