【问题标题】:C++ is overloading my overloaded operators?C++ 正在重载我的重载运算符?
【发布时间】:2015-04-04 20:00:28
【问题描述】:

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

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 和一个对象。它如何能够获取对象和整数?我希望我不会在这里忽略一些愚蠢的明显的东西!

【问题讨论】:

    标签: c++ operator-overloading implicit-conversion


    【解决方案1】:

    您已经定义了从 intInt 的隐式转换:

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

    因此编译器可以确定Int + int 应该调用Int + Int(int)

    如果您不希望这样,无论出于何种原因,您都可以将构造函数标记为explicit

    【讨论】:

    • 啊!我懂了!但是,如果构造函数没有返回值,std::cout 如何得到答案?
    • @Jeff-Russ:构造函数的“返回值”是构造的对象。而&lt;&lt; 的参数是operator+(Int, Int) 的结果,其值为int,而不是Int
    • 好的,知道了。非常感谢!!
    【解决方案2】:

    罪魁祸首是这个人:

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

    由于它没有被标记为explicit,这是一个隐式构造函数,编译器会在你有一个int但一个函数(或运算符)期待一个Int的上下文中自动调用它.

    因此,例如,编译器解析

    cout <<  3 + int1 << endl;
    

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

    自动。

    使用explicit 关键字来强制这种代码更显式通常是一个好主意,但是应该提到的是,隐式构造在非常突出的代码中大量使用,尤其是 C++ 标准库,例如,std::string 可以从const char* 隐式构造。这是方便性和清晰性之间的权衡。

    【讨论】:

    • 也谢谢你。现在我明白了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-27
    • 1970-01-01
    • 1970-01-01
    • 2016-04-08
    • 2012-06-02
    • 2014-01-14
    • 2013-03-23
    相关资源
    最近更新 更多