检测默认构造函数是否有效

Detecting Default constructor works or not

本文关键字:有效 是否 构造函数 默认 检测      更新时间:2023-10-16

我在Foo.h中有一个简单的类定义,比如:

template <typename T>
class Foo
{
  public:
    Foo();
  private:
     char *topPtr;
}

我已经实现了Foo.cpp类:

template <typename T>
Foo<T>::Foo(){
    cout<<"default constructor is runned"<<endl;
    this.topPtr=NULL;
    if(topPtr==NULL){cout<<"topPtr is null"<<endl;}
}

现在,为了查看我的Stack构造函数是否运行,我编写了一个简单的main.cpp,比如:

#include <iostream>
#include "Foo.h"
using namespace std;
int main(){
    Foo<int> foo1();
    return 0;
}

我应该在我的终端上看到"默认构造函数已运行""topPtr为null"消息,但我什么都没有。有人帮我吗?提前谢谢。

语句Foo<int> foo1();声明了一个返回Foo<int>的函数foo1。你应该做:Foo<int> foo1{};

请参阅:链接

您的this.topPtr=NULL;应该是this->topPtr=NULL;

您不需要(),通过使用它,您声明了一个名为foo1的函数,该函数返回Foo<int>,不接受任何参数。

Foo<int> foo1; // It calls default constructor

 

要使用this指针,您应该使用->而不是.

this->topPtr // to dereference this pointer