我有一个函数(modShape),它将一个抽象基类(Shape)作为参数;在函数中我想制作输入对象的副本,修改副本,并将副本重新分配给输入对象,以便修改保留在modShape的范围之上.
我已经设置了一个clone()成员函数来制作初始副本,这似乎运作良好.接下来,我使用doubleArea()成员函数修改副本,并尝试将其复制回输入对象.
基类和派生类在header.h中定义:
#ifndef HEADER_H_
#define HEADER_H_
#include <iostream>
#include <cmath>
using namespace std;
// Abstract base class.
class Shape {
public:
// Virtual functions
virtual double area() { return 0; }
virtual double perimeter() { return 0; }
virtual void doubleArea() { /* do nothing */ }
virtual Shape* clone() const = 0;
};
// Derived class.
class Circle: public Shape {
private:
double radius;
public:
Circle (double r) : radius(r) {}
double area() { return (M_PI*pow(radius,2)); }
double perimeter() { return (M_PI*2*radius); }
void doubleArea() { radius *= pow(2,0.5); }
Circle* clone() const { return new Circle(*this); }
};
#endif
函数modShape和测试代码在main.cpp中:
#include <iostream>
#include "header.h"
using namespace std;
void modShape(Shape &inShape) {
// Make new Shape* from clone of inShape
// and double its area.
Shape* newShape = inShape.clone();
newShape->doubleArea();
cout << "newShape's area (after doubling): " << newShape->area() << endl;
// Copy newShape to inShape.
inShape = *newShape;
cout << "newShape copied to inShape (circ)." << endl;
cout << "inShape's area in modShape: " << inShape.area() << endl;
};
int main() {
Circle circ(2);
cout << "circ's initial area (in main): " << circ.area() << endl;
modShape(circ);
cout << "circ's final area (in main): " << circ.area() << endl;
return 0;
}
我从这个函数得到的输出是:
circ’s initial area (in main): 12.5664
newShape’s area (after doubling): 25.1327
newShape copied to inShape.
inShape’s area in modShape(): 12.5664
circ’s final area (in main): 12.5664
很明显,分配inShape = * newShape并不像我期望的那样工作.我的猜测是使用的赋值运算符是Shape类,因此不会从派生类中复制成员变量(如radius)?如果是这种情况,我想我想定义一个赋值运算符,它将“知道”对象是派生类,即使它们被定义为基类,但我不知道如何做到这一点.或者如果有更好的解决方案,请告诉我!任何意见是极大的赞赏.
更新:
看起来像切片是问题,现在我需要弄清楚如何避免它.我想如果我定义我的函数来接受一个指针,事情会更好:
void modShape2(Shape* inShape) {
Shape* newShape = inShape->clone();
cout << inShape->area() << endl;
inShape = newShape;
cout << inShape->area() << endl;
}
我设置为:
Circle *circ2 = new Circle(1);
cout << "circ2's initial area (in main): " << circ2->area() << endl;
modShape2(circ2);
cout << "circ2's final area (in main): " << circ2->area() << endl;
这里产生的输出是
circ2’s final area (in main): 3.14159
3.14159
6.28319
circ2’s final area (in main): 3.14159
在这种情况下,似乎副本正在发生而没有切片,因为区域在modShape2函数内被加倍,但是当我们出于某种原因退出modShape2的作用域时,更改不会被执行.我真的很困惑!
最佳答案 问题
你已经确定了它.该错误是由以下语句引起的,该语句导致object slicing:
inShape = *newShape;
因此,只复制Shape基础对象中的成员.不复制不属于基类的区域.
鞋底怎么样?
不建议定义虚拟赋值运算符,因为类T的此运算符的通常签名是:
T& operator= (const T& r);
这样你就会遇到返回类型的麻烦.
一个更简单的解决方案是使用虚拟复制功能(与克隆功能类似的原理):
class Shape {
...
virtual void copy(const Shape&r) = 0;
};
它将针对派生对象实现,检查类型是否匹配并使用类型的赋值运算符.例如:
void copy(const Shape&r) override {
if (dynamic_cast<const Circle*>(&r))
*this = *dynamic_cast<const Circle*>(&r);
else throw (invalid_argument("ouch! circle copy mismatch"));
}
在这里an online demo.