Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/125.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
重写运算符多个参数 我一直在玩C++,发现了一些我无法解释的东西。_C++ - Fatal编程技术网

重写运算符多个参数 我一直在玩C++,发现了一些我无法解释的东西。

重写运算符多个参数 我一直在玩C++,发现了一些我无法解释的东西。,c++,C++,使用以下代码: #include <iostream> using namespace std; class Foo { private: int bar; public: Foo():bar(0){} Foo(int a):bar(a){} ~Foo(){} int getVal() const { return bar;} }; bool operator < (const Foo& a, const Foo&

使用以下代码:

#include <iostream>
using namespace std;

class Foo
{
private:
    int bar;
public:  
    Foo():bar(0){}
    Foo(int a):bar(a){}
    ~Foo(){}
    int getVal() const { return bar;}
};

bool operator < (const Foo& a, const Foo& b){
    std::cout << a.getVal() << " " <<  b.getVal() << std::endl;
    return a.getVal() < b.getVal();
}

int main() {
    Foo a(12);
    Foo b(15);

    if(NULL < (a,b) ) /*  */
      std::cout << "lesser" << std::endl;
    return 0;
}
如果我把条件改成

a < b or operator<(a,b)
<>我认为这可能是一些编译器的东西,但我想在C++ >代码> null < /C>中确定

< P>。当你做比较时,C++在左边应用<>代码> fo(int)< /c>构造函数,在右边看到结果。

要禁止将
NULL
转换为
Foo
时的行为,请在构造函数上使用指示符(需要C++11或更高版本):

此代码

 if(NULL < (a,b) ) /*  */
      std::cout << "lesser" << std::endl;
变成

 if(0 < 0) ) /*  */
      std::cout << "lesser" << std::endl;
if(0<0))/**/

STD::你可以用逻辑>代码解释这个吗?因为在C++中,任何非零值都是真的< /C>。我认为这不太正确。也许是用python这样的动态语言。如果这是真的,那么
(a,b)
的类型是什么?@DKG您的解释在这种情况下是正确的,如果(NULL<(a这一行实现什么?如果(NULL<(a,b))
,这个问题指出了一个有趣的行为。否决票有点苛刻。我不打算将其应用于生产代码或任何东西,只是想知道它为什么会这样。这是我学到的一个教训!使用
nullptr
!!二进制运算符位于两个操作数之间
a,b
表示
运算符,(a,b)
结果是
的操作数谢谢,我一直认为逗号用作分隔符,但直到它也可以用作运算符。我不认为有任何从
nullptr
int
的隐式转换,因此,根据实现对
NULL
的选择,代码甚至可能无法编译。我认为你链接的答案是错误的,因为C++11@MetalRidersMicrosoft在
assert
宏中使用coma运算符:
#define assert(_Expression)(void)(!!(_Expression))| |(_wassert(#CRT_WIDE(#u Expression),CRT_WIDE(u FILE_u),u LINE_u),0))
c++98中存在的显式
构造函数。请参阅Visual studio 2010上的@M.M,我正在使用它,
NULL
被定义为0。此版本中甚至存在know
nullptr
。在更高版本中,
NULL
是否定义为
nullptr
?这可能会破坏很多代码!
explicit Foo(int a):bar(a){}
 if(NULL < (a,b) ) /*  */
      std::cout << "lesser" << std::endl;
 if(NULL < true ) /*  */
      std::cout << "lesser" << std::endl;
if(NULL < 1 ) /*  */
      std::cout << "lesser" << std::endl;
 if(0 < 1 ) /*  */
      std::cout << "lesser" << std::endl;
 if(NULL < false ) /*  */
      std::cout << "lesser" << std::endl;
 if(0 < 0) ) /*  */
      std::cout << "lesser" << std::endl;