[英]Why does the pointer object did not call default constructor
#include<iostream>
using namespace std;
class test
{
public:
test(){cout<<"Constructor called ";}
};
int main()
{
test a,*b;
return 0;
}
I expected the constructor to be called two times.我希望构造函数被调用两次。 Why does a pointer object did not call the default constructor
为什么一个指针object没有调用默认构造函数
A pointer is just a pointer.指针只是一个指针。 It can point to an object but it does not necessarily do so.
它可以指向一个 object 但它不一定这样做。 Declaring a pointer does not automagically create an instance.
声明指针不会自动创建实例。 Your pointer is not initialized to point anywhere.
您的指针未初始化为指向任何地方。
For a far-fetched analogy consider I give you a paper on which it is written: "My wallet".对于一个牵强的类比,考虑一下我给你一张纸,上面写着:“我的钱包”。 I didn't give you any money, I just gave you a "pointer" to where you can find money (not necessarily, only if there actually is money in my wallet).
我没有给你任何钱,我只是给了你一个“指针”,你可以在哪里找到钱(不一定,只有当我的钱包里确实有钱时)。 For your code the better analogy is: I give you an empty piece of paper.
对于您的代码,更好的类比是:我给您一张空纸。 In any case, giving you a "pointer" to where you can find money, unfortunately does not create money in my wallet:(
无论如何,给你一个“指针”指向你可以在哪里找到钱,不幸的是不会在我的钱包里创造钱:(
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.