2015-04-04 103 views
1

今天我注意到了一些东西。如果我创建三个版本的重载+运算符来处理每一个组合(对象+原始,原始+对象,对象+对象)一切都按预期执行:C++重载我的重载操作符?

class Int 
{ int data; 
    public: 
    Int(){data = 0; }; 
    Int (int size){ data = size; }; 
    friend int operator+(Int, Int); 
    friend int operator+(int, Int); 
    friend int operator+(Int, int); 
}; 
int operator+(Int lInt, Int rInt) 
{ cout <<"first version. "; 
    return rInt.data + lInt.data; 
} 
int operator+(int lInt, Int rInt) 
{ cout <<"second version. "; 
    return rInt.data + lInt; 
} 
int operator+(Int lInt, int rInt) 
{ cout <<"third version. "; 
    return lInt.data + rInt; 
} 
int main(int argc, char *argv[]) { 

    Int int1 = 1; 

    cout << int1 + int1 <<endl; // prints "first version. 2" 
    cout << 3 + int1 << endl; // prints "second version. 4" 
    cout << int1 + 3 << endl; // prints "third version. 4" 
} 

但如果我删除第二和第三个版本中,它仍作品!?!

class Int 
{ int data; 
    public: 
    Int(){data = 0; }; 
    Int (int size){ data = size; }; 
    friend int operator+(Int, Int); 
}; 
int operator+(Int lInt, Int rInt) 
{ cout <<"first version. "; 
    return rInt.data + lInt.data; 
} 
int main(int argc, char *argv[]) { 

    Int int1 = 1; 

    cout << int1 + int1 <<endl; // prints "first version. 2" 
    cout << 3 + int1 << endl; // prints "first version. 4" 
    cout << int1 + 3 << endl; // prints "first version. 4" 
} 

如何为我的重载+运营商,这意味着接受两个对象,能够采取一个int和对象。它如何能够采取对象和int?我希望我不会在这里忽略一些显而易见的东西!

回答

0

罪魁祸首是这个家伙:

Int (int size){ data = size; }; 

既然没有标记explicit,这是一个隐含的构造函数,编译器会自动推调用它在你有一个int而是一个函数上下文(或运营商)期待Int

因此,举例来说,编译器解决

cout << 3 + int1 << endl; 

cout << Int(3) + int1 << endl; 

自动。

使用explicit关键字来强制这种类型的代码更加明确通常是一个好主意,但是,应该指出,隐式构造主要用于非常突出的代码中,最显着的是C++标准库,其中,例如,std::string可以隐含地从const char*构建。这是便利性和清晰度之间的折衷。

+0

也感谢你。现在我明白了! – 2015-04-04 20:14:22

+0

不客气:) – bgoldst 2015-04-04 20:15:32

0

您已经定义从int的隐式转换到Int

Int (int size){ data = size; }; 

因此编译器能弄清楚,Int + int应该叫Int + Int(int)

如果你不想这样做,无论出于何种原因,你会将构造函数标记为explicit

+0

AHH!我懂了!但是,如果构造函数没有返回值std :: cout如何得到答案? – 2015-04-04 20:11:34

+0

@ Jeff-Russ:构造函数的“返回值”是构造对象。并且'<<'的参数是'operator +(Int,Int)'的结果,它的值是一个'int',而不是'Int'。 – rici 2015-04-04 20:12:10

+0

好的,明白了。非常感谢!! – 2015-04-04 20:13:48