以下代码的作用是什么 [英] what does the following code do
问题描述
对于以下C ++代码:
class X {
public :
X(){cout<< constr;}
};
main(){
X obj();
}
' X obj()'期间会发生什么。它不会调用默认的无参数构造函数。实际上,此语句根本不创建对象,因为在此语句之后,您可以在obj上调用任何X成员。但是语句也没有给出编译错误。
这个类有一个自动生成的默认构造函数,因为你没有提供任何其他的构造函数。自动生成的构造函数的作用如下:它只调用基类的默认构造函数和类的非pod数据成员。由于此类没有任何基类或任何非pod数据成员,因此自动生成的默认构造函数不执行任何操作。当使用优化编译时,这个构造函数调用最有可能被优化掉。
你在main中定义一个函数原型,这就是为什么没有创建对象的原因:
<前lang =cs> main()
{
X obj();
}
要解决此问题,请使用以下语法创建对象:
main()
{
X obj;
}
这是C ++解析中出现的一个奇怪之处。如果构造函数有参数,则括号适合放置在构造调用周围。不要对默认的构造对象使用括号。
我完全同意在通过默认构造函数创建类实例时,我们不使用括号,ii,我们创建类的实例X如下:
X obj;
但令我感到困惑的是:当我们给出以下内容时会发生什么
X obj();
此语句不会产生编译时错误。
此语句不会调用默认构造函数 obj 的类。
在此语句之后,无法在 obj 上访问类成员 - 编译器说请求'obj'中的成员,非类型'X()'。
那么实际发生了什么如果没有创建对象,则在此语句中。
For the following C++ code :
class X{
public :
X() {cout<<"constr" ;}
} ;
main () {
X obj() ;
}
What happens during 'X obj()'. It does not invoke the default argument-less constructor. In fact this statement does not create an object at all because after this statement you can invoke any X member on obj. But neither does the statement give a compilation error.
This class has an automatically generated default constructor because you haven't provided any other constructors. What the automatically generated constructor does is the following: It just calls the default constructor of the base classes and the non-pod data members of the class. Since this class doesn't have any base classes or any non-pod data members the auto-generated default constructor does nothing. When compiled with optimization this constructor call is most probably optimized away.
You are defining a function prototype in main, that is why no object is being created:
main () { X obj() ; }
To correct this, use this syntax to create your object:
main () { X obj; }
This is one of the oddities that appears in C++ parsing. If your constructor had parameters, then the parenthesis would be appropriate to place around your construction call. Don't use parenthesis for a default constructed object.
I fully agree that while creating a class instance via a default constructor, we do not use parenthesis, i.i., we create an instance of class X as follows :
X obj ;
But what I am confused about is this : what happens when we give the following
X obj() ;
This statement does not give a compile-time error.
This statement does not call the default constructor of the class for obj either.
After this statement, a class member can not be accessed on obj - compiler says that request for member in ‘obj’, which is of non-class type ‘X()’.
So what is actually happening at this statement if the object is not being created.
这篇关于以下代码的作用是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!