c++ - 指针和引用 + 重载运算符

标签 c++ pointers operator-overloading

假设我有一个程序,我想在其中求解方程(类似这样)

Number x;
Func fw = x * 4 + x * x;
std::cout << fw(6.0) << "\n\n";

因此,我从编写抽象基类开始,其中我拥有求解该方程式所需的所有内容。

class Base
{
public:
    Base(){};
    virtual Base* operator*(Base& x) = 0;
    virtual Base* operator*(double x) = 0;
    virtual Base* operator+(Base& x) = 0;
};

和类(class)编号

class Number : public Base
{
public:
    virtual Base* operator*(Base& x);
    virtual Base* operator*(double x);
    virtual Base* operator+(Base& x);
};

和带有复制构造函数的 Func 类(或者至少,我认为它是一个复制构造函数)

class Func: public Base
{
    Base * func;
public:
    Func(Base* other)
    {
        func = other;
    }

    Func(Base& other)
    {
        func = &other;
    }

    virtual Base* operator*(Base& x){}

    virtual Base* operator*(double x){}

    virtual Base* operator+(Base&){}

};

所以,我的问题。我的程序适用于 x*xx*4,但是当我尝试组合它们时 x*x + x*4 我有一个问题。

很明显(或者不是)问题是什么。在 x*x 之后,我的程序返回指针 (Base*),而在我的重载运算符中我只有 (Base&)。 所以程序无法匹配任何重载运算符。

这是 CLion 向我展示的二元运算符 + 不能应用于 Base* 和 Base* 类型的表达式

因此,解决方案可以是再次重载运算符,但使用参数(Base*),但我希望有更好的方法来解决这个问题。有吗?

最佳答案

是的,有:编写一个使用值或引用语义而不是指针语义的包装类。例如,

class BaseRep // I've renamed your `Base` class
{
public:
    BaseRep(){};
    virtual std::unique_ptr<BaseRep> multiply(const BaseRep& x) = 0;
};

class Base
{
    std::unique_ptr<BaseRep> ptr;
public:
    Base(std::unique_ptr<BaseRep> &&p):ptr(p) {}
    BaseRep& rep() { return *ptr; }
    const BaseRep& rep() const { return *ptr; }
    // and other stuff
};

Base operator*(const Base &x, const Base &y)
{
    return Base( x.rep().multiply(y.rep()) );
}

关于c++ - 指针和引用 + 重载运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33191493/

相关文章:

c++ - 重载成员访问运算符有什么用?

c++ - 如何获取Microsoft TTS语音的耗时?

c - 传递指向函数的指针没有按预期工作

c++ - 运算符<有什么用?

pointers - 调用结构函数给出 "cannot refer to unexported field or method"

c - 指向多维数组的指针错误: Expression must have pointer-to-object type

C# 运算符重载、重写字符串?

c++ - 如何在 Visual Studio 2012 中禁用大括号补全?

c++ - 使用 OpenSSL 库将 C++ 中的 BIO* 转换为 PKCS7*

c++ - fatal error LNK1104 : cannot open file