从常量指针到指针的转换
conversion from const pointer to pointer
我正在尝试将矩形构造函数 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
。
- 正在将指针转换为范围
- 如何理解将半精度指针转换为无符号长指针和相关的内存对齐
- C++:Lambda 函数指针转换的用例是什么?
- 如何将 int 指针转换为浮点指针
- 为什么在将 void 指针转换为整数指针时出现分段错误
- 将(N 个字节)无符号字符指针转换为浮点数和双 C++
- 我们可以在不知道其真实类型的情况下将基类指针转换为派生类指针吗?
- C++中数组大小未知的指针转换
- Antlr cpp 运行时 任何错误的指针转换?
- std::flush可以用于将对象指针转换为其封闭数组指针吗
- C 指针转换会导致内存访问冲突
- 模板类实例化中的指针转换无效
- 函数调用歧义(用户定义的转换和 Derived2Base 指针转换)
- 如何将 void(*)() 类型的指针转换为 void*
- 数组到指针转换期间的临时具体化
- 直接为浮点变量分配十六进制整数与通过指针转换分配之间的区别
- 将基类指针转换为派生的类指针
- 应对 std::字符串中的 std::<char>指针转换后的向量
- 在编译时将函数指针转换为 std::uintptr_t
- 将基类指针转换为未知派生类指针