之前在写博客的时候,都没注意过编译器的问题。这次注明:code::blocks,gcc版本:4.9.2;
今天在overflow上面看到一个问答,说新建一个不带参数的对象加括号和不加括号,是有区别的?之前我一直以为是没区别的,就实验了下,代码如下:
#include<iostream>
using namespace std;
class Rectangle
{
private:
int m_w, m_h;
public:
Rectangle(){cout << "default" << endl;}
Rectangle (int w, int h)
{
cout << "带参构造函数" <<endl;
}
};
int main()
{
cout << "Rectangle *rect1 = new Rectangle(3,4); //";
Rectangle *rect1 = new Rectangle(3,4);
cout << "Rectangle rect2(2,3); //";
Rectangle rect2(2,3);
cout << "Rectangle rect3(); //";
Rectangle rect3(); //这儿没有去调用构造函数类中自己定义的构造函数;据说编译器把它当作了函数来处理;
void b(); //上一句的代码就类似于执行了这么一个函数声明;
cout << endl;
cout << "Rectangle rect4; //";
Rectangle rect4;
cout << "Rectangle *prec = new Rectangle; //";
Rectangle *prec = new Rectangle; //加不加括号都行;
return 0;
}
输出如下:
Rectangle *rect1 = new Rectangle(3,4); //带参构造函数 Rectangle rect2(2,3); //带参构造函数 Rectangle rect3(); // Rectangle rect4; //default Rectangle *prec = new Rectangle; //default
网上是这么说的,29行的代码,编译器认为是一个 返回值为Rectangle,函数名为rec3的函数声明,那既然认为是函数声明,当然也就不会去调用构造函数了。为什么呢?
——————————因为:
it is that the standard requires the compiler to interpret anything that might be a function declaration as a function declaration, to prevent ambiguity.
那么,为什么创建带参数的对象时(例如:rect2(2, 3)),带参数的构造函数就能够正常的使用了呢?按理说,编译器也可以把它解释为一个函数的声明?。。。少侠, 等等!编译器能把它解释为函数的声明吗?你再仔细看看!这括号里面可是数字啊。乍一看又有点像调用,但是别忘了前面还有一个Rectangl呢,所以,不是声明也不是调用,那么,就只能构造了呗。