简体   繁体   English

为什么指针 object 没有调用默认构造函数

[英]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.

相关问题 为什么这会调用默认构造函数? - Why does this call the default constructor? 复制构造函数是否调用默认构造函数来创建对象 - Does copy constructor call default constructor to create an object 为什么复制构造函数调用其他类的默认构造函数? - Why does copy constructor call other class' default constructor? 为什么调用重载的构造函数会导致调用默认构造函数? - Why does calling an overloaded constructor cause a call of the default constructor? 为什么我的对象声明不调用默认构造函数? - Why doesn't my object declaration call the default constructor? 为什么构造函数调用取决于默认析构函数的存在? - Why does the constructor call depend on the default destructor's presence? 为什么空向量调用值类型的默认构造函数? - Why does an empty vector call the value type's default constructor? 为什么在没有默认构造函数的情况下使用带有 class 的指针而不使用指针 - Why does using a pointer with a class with no default constructor work here and not using no pointer 为什么要尝试调用默认构造函数? - Why is this attempting to call the default constructor? 为什么使用默认构造函数构造的对象的`sizeof`始终为1? - Why does taking the `sizeof` of an object constructed with a default constructor always result in 1?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM