为什么我的默认构造函数返回bool?

时间:2012-10-09 00:06:23

标签: c++ constructor boolean

  

可能重复:
  Error on calling default constructor with empty set of brackets

当我运行此命令时,我收到编译器警告:34 [警告] .Rational test4()的地址将始终评估为true。但我试图使其默认构造函数是有理数0/1。第34行是int main()行:cout<< TEST4;

#include <iostream>

using namespace std;

class Rational
{
public:
       Rational();

       friend ostream& operator <<(ostream& out,Rational rational1);


private:
        int numerator;
        int denominator;

};

int main()
{
    //Rational test1(24,6), test2(24);
    Rational test4();
    //cout << test1<< endl;
    //cout << test2<< endl;
    cout << test4;
    system("pause");
}

Rational::Rational() : numerator(0), denominator(1)
{ 
    //empty body
}

ostream& operator <<(ostream& out,Rational rational1)
{
       out << rational1.numerator <<"/"<<rational1.denominator;
       return out;
}

1 个答案:

答案 0 :(得分:1)

程序打印“1”的原因是因为Rational test4();声明了一个函数指针。那么std::cout如何打印函数指针?它涉及自动转换。首先看一下普通的旧数据指针。 I / O机制没有用于打印double*指针或MyClass*指针或可能出现的任意数量指针的机制。 I / O机器可以做的是打印void*指针的机制。由于隐式转换,同样的机制适用于double*MyClass*指针,因为所有指针都转换为void*指针。

函数指针不会转换为void*。函数指针不是指针!唯一可用的转换是布尔值。转换为布尔值就是让你做if (function_pointer) do_something();之类的东西你的函数指针不是空的,所以在转换为bool时,它变成true,打印为1

解决方案很简单:将Rational test4();更改为Rational test4;`,