Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/137.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 复制引用对象并调用虚方法C++;_C++_Pointers_Inheritance - Fatal编程技术网

C++ 复制引用对象并调用虚方法C++;

C++ 复制引用对象并调用虚方法C++;,c++,pointers,inheritance,C++,Pointers,Inheritance,这里,MyLineShape对象b通过引用传递到此函数(在MyCustomWidget类中)myShape是一个Shapes指针 void MyCustomWidget::setDrawingObject(Shapes &b){ myShape = &b; myShape->setPoint1(); } 它可以工作,即调用myShapes setPoint1()方法。但是当我在MyCustomWidget类的其他部分尝试使用 myShape->setPo

这里,
MyLineShape
对象
b
通过引用传递到此函数(在
MyCustomWidget
类中)
myShape
是一个
Shapes
指针

void MyCustomWidget::setDrawingObject(Shapes &b){
   myShape = &b;
   myShape->setPoint1();
}
它可以工作,即调用myShapes setPoint1()方法。但是当我在MyCustomWidget类的其他部分尝试使用

myShape->setPoint1();

程序崩溃了。也许这是因为范围
setPoint1()
是一个虚拟函数,因为不同的形状类分别实现它。所以我想做的是在
setDrawingObject
函数中告诉它从引用中接收到了哪个对象,并复制该类型的对象,以便稍后在这个类的其他函数调用中使用。如何做到这一点?

听起来你只是有一个悬空的指针。无论您调用的对象是什么,当您仍然有指向它的指针时,它都会被销毁。解决这个问题有两种常见的方法。首先,只需使用
共享\u ptr

void MyCustomWidget::setDrawingObject(shared_ptr<Shapes> b) {
   myShape = b;
   myShape->setPoint1();
}

无论哪种方式,都要避免让myShape成为一个
Shapes*

当程序崩溃时,您会收到什么样的错误消息?你能告诉我们你的程序在哪里崩溃吗?这会有很大帮助。请看一看:shapeClasses branch上的github.com/advancement/WaterPaint.git。要查看的文件是mainwindow.cpp和MyCustomWidget.cpp,您说过“但在这个MyCustomWidget类的其他部分中时”。你的代码哪一部分崩溃了?请详细解释。您不是在复制引用的对象,而是在使用myShape->setPoint1()@eagleye时在mousevent方法中获取它的地址。@Cubia。不,我不是在为你调试整个项目。如果你想再问一个问题,那就再问一个问题。我并不认为你更容易理解。我会尝试更多,让你知道
void MyCustomWidget::setDrawingObject(Shapes& b) {
    myShape.reset(b.clone());  // myShape is a unique_ptr<Shapes>
    myShape->setPoine1();
}