从覆盖方法返回派生类,声明为返回基本副本

时间:2015-06-11 08:41:50

标签: c++

这又是一个经常出现的问题。有人知道一个简单的方法吗?想象一下,我有以下几点:

class Base
{
    public:
        ...
        Base property(const std::string& name)=0;
};
class Derived:public Base
{
    public:
        Derived();
        Derived(const Derived&& val);
        Base property(const std::string& name)
        {
            Derived z;
            return z;
        }
 }

Derived :: property返回(内部)Derived副本而不是仅返回Base部分副本,并调用Derived移动构造函数?

可能是一个愚蠢的问题,但实际上我找不到解决方案。为什么在返回时复制构造函数不要复制专门的类?

谢谢!

2 个答案:

答案 0 :(得分:3)

你不能这样做。

从概念上返回值(忽略RVO和移动语义)意味着使用声明函数返回的类型的复制构造函数来复制您返回的任何内容。如果您返回Base,则会生成Derived类型的副本,并且您将丢失该对象的Derived部分。这称为切片

如果您想将Base对象作为override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil) notificationCenter.addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil) } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.removeObserver(self, name: UIKeyboardWillShowNotification, object: nil) notificationCenter.removeObserver(self, name: UIKeyboardWillHideNotification, object: nil) } 返回,则需要使用指针。

答案 1 :(得分:0)

我可以找到哪些搜索类似的东西(与X3liF,TartanLlama和其他响应相关)

#define overridable(T) ovr<T>
#define return_overload_allowed(TYPE) friend struct ovr<TYPE>; virtual void* clone() const
#define return_overload_basic_allowed(TYPE) friend struct ovr<TYPE>; virtual void* clone() const{return new TYPE(*this);}

template<typename T> struct ovr
{
	T* _obj;
	ovr(const T& t)
	: _obj(reinterpret_cast<T*>(t.clone()))
	{;}
	ovr(ovr<T>&& v)
    : _obj(v._obj)
    {
	    v._obj=nullptr;
    }
	operator T&()
	{
		return *_obj;
	}
	virtual ~ovr()
	{
		delete _obj;
	}
};


class BASE
{
	return_overload_basic_allowed(BASE);
public:
	virtual overridable(BASE) method1();
	virtual ~BASE();
};

class DERIVED: public BASE
{
	return_overload_basic_allowed(DERIVED);
public:
	virtual overridable(BASE) method1()
	{
		DERIVED a;
		return a;
	}
	virtual ~DERIVED();
	
};

DERIVED a;
auto x = a.method1();
BASE& really_derived = x;

编译好。但是不满足实际和聪明的要求...... :(

相关问题