新的类对象,运算符重载

时间:2018-01-26 06:35:29

标签: c++ operator-overloading

我正在尝试创建与构造函数做同样事情的运算符。 我为这个类创建了重载的输出运算符<<,这很简单。

我只想输入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,我想创建一个值为两倍的新对象(例如)。

3 个答案:

答案 0 :(得分:0)

foo& operator+(int x, foo& f) {   
    f tmp = new foo(x); ////here foo* temp = new foo(x);f is a reference which can not modify tmp
    return tmp;
}

答案 1 :(得分:0)

你几乎就在那里。

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

#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 ++中,我们通常更喜欢将对象视为值。

答案 2 :(得分:0)

这将创建一个新的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