【问题标题】:New class object, operators overloading新类对象,运算符重载
【发布时间】:2018-01-26 06:35:28
【问题描述】:

我正在尝试创建与构造函数相同的操作符。 我为这个类创建了重载输出运算符<<,这很容易。

我只想输入nameOfObject+(value) 来创建foo 类的新实例。

我试过这个:

foo& operator+(int x, foo& f) {
    f tmp = new foo(x);
    return tmp;
}

但我收到错误消息说我需要在tmp 之后使用;

#include <iostream>
#include <memory>

class foo {
    private: 
        int x;
    public: 
        foo(int x) { this->x = x; }
        int getX() { return this->x; }        
};

std::ostream& operator<< (std::ostream& text, foo& f) {
    text  << f.getX();
    return text;
}

int main()
{
    foo bar(2);
    std::cout <<bar; //returns 2

    return 0;
}

UPDATE_1:
例如,我的班级中有 heightOfTheTree 变量。使用foo tree1(5) - 普通构造函数我只想将 5 分配给我的变量。但是使用foo tree2+5,我想创建一个值乘以两倍的新对象(例如)。

【问题讨论】:

  • 使用f tmp = new foo(x); 向我表明您并不精通该语言的基础知识。阅读a good book对你有好处。
  • 类型叫什么,参数叫什么?
  • 这个类似的问题可能会引起人们的兴趣:how to add three objects of same class in c++?(顺便说一句,标记为重复),我在其中为operator+ 重载提出了多种解决方案。
  • 您的问题表明您希望表达式bar + n 返回bar 的副本,但您真的不希望它返回值为bar.getX() + n 的bar 的副本吗?

标签: c++ operator-overloading


【解决方案1】:

你快到了。

它应该看起来像这样。内嵌评论:

#include <iostream>
#include <memory>

class foo {
    private: 
        int x;
    public: 
        foo(int x) : x(x) { }

        // add a const modifier because this function does not modify foo
        int getX() const { return this->x; }        

        // it usually makes sense to implement + in terms of +=
        foo& operator+=(int arg)
        {
            x += arg;
            return *this;
        }
};

// implement + in terms of += on a copy
foo operator+(foo l, int r)
{
    l += r;
    return l; 
}

// for this class, make addition commutative. i.e x+y == y+x
foo operator+(int l, foo const& r)
{
    return r + l;
}

// add a const modifier because we expect and demand that this operation
// will not modify f
std::ostream& operator<< (std::ostream& text, foo const& f) {
    text  << f.getX();
    return text;
}

int main()
{
    foo bar(2);
    std::cout <<bar; //returns 2

    foo bar2 = bar + 5;
    std::cout <<bar2; //returns 7

    foo bar3 = 5 + bar2;
    std::cout <<bar3; //returns 12

    return 0;
}

请注意,我们不使用new 来复制对象。 Java 和 C# 要求这样做。在 c++ 中,我们通常更喜欢将对象视为值。

【讨论】:

  • 小误会,您的代码正在为已创建的对象添加一些价值。我希望我的代码在 + 符号之后创建具有值的新对象。谢谢。
  • @sqlMasterSOon 听起来你的意思是你希望 operator+ 表现得像一个复制构造函数?
  • 是的,这就是我想要的。
【解决方案2】:

这将创建一个新的 foo 对象。

foo operator+(foo& f, int x) {
    return foo(f.getX() + x);
}

//Usage
foo bar(2);
foo test = bar + 5;
std::cout << test; //outputs 7

【讨论】:

  • 看起来不错,但如何使它像foo test+5。您的代码正在使用另一个创建新对象。如何在不使用另一个对象的情况下创建新对象?有可能吗?
  • @sqlMasterSOon 不确定我理解。 foo test+5;foo test(5) 之间有什么区别?
  • 因为例如我的班级中有heightOfTheTree 变量。使用foo tree1(5) - 普通构造函数我只想将5 分配给我的变量。但是使用foo tree2+5,我想创建一个值乘以两倍的新对象(例如)。
  • @sqlMasterSOon 你能编辑你的问题并在代码中放一个实际的使用示例吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-13
  • 2016-07-15
  • 2012-06-16
  • 1970-01-01
  • 1970-01-01
  • 2018-02-22
相关资源
最近更新 更多