gpt4 book ai didi

c++ - 需要解决限制 : abstract class cannot be used for return types

转载 作者:行者123 更新时间:2023-11-28 00:14:03 26 4
gpt4 key购买 nike

我有一个 C++ 类,我希望使用 pImpl 指针隐藏其实现。大部分工作已完成,一切正常,除了运算符“+=”返回同一类的对象。该运算符函数必须在类中。问题是当做成一个抽象类时,没有成员函数可以返回那个类的对象,所以'+='是不允许的。

我正在寻求有关处理此限制的建议。我更喜欢一种不需要更改使用此类的现有代码的方法。如果没有这种方式,还能做什么?

这是我希望抽象的类的简化版本:

class AClass 
{
public:
AClass( int x0, int y0);
~AClass(void);
void operator=(const AClass &A2);
AClass operator+(const AClass &A2);
void operator+=(const AClass &A2);
protected;
int x;
int y;
};

AClass AClass::operator+(const AClass &A2) { AClass AOut(A2); AOut += A2; return AOut; }
AClass AClass::operator+=(const AClass &A2) { this->x += A2.x; this->y += A2.y; }


// 'operator+' is necessary to perform the following operation on AClass objects. i.e.
A = B + C;
// 'operator+=' is necessary to perform the following operation on AClass objects. i.e.
A += B;

最佳答案

EXCEPT for an operator '+=' which returns a object of the same class

operator+=(以及其他赋值运算符)需要返回 AClass& 而不是 AClass

参见例如Scott Meyers “Effective C++” 第 10 项:

Have assignment operators return a reference to *this

这样可以避免按值返回类的问题,并使您的代码更接近 C++ 准则。

P.S. 然而operator+=似乎并不是唯一的一点。例如,operator+ 有同样的问题,不应该返回一个引用。因此,您可能会将这篇文章视为对问题的字面回答,而不是问题的解决方案。

关于c++ - 需要解决限制 : abstract class cannot be used for return types,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31466554/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com