检测默认构造函数是否有效
Detecting Default constructor works or not
我在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
相关文章:
- 如果变量名称不跟在 char* 后面,const char* 是否有效?
- 钳制迭代器是否有效
- 检查由括号、方括号和大括号组成的一组方括号是否有效?
- 在函数内创建的对象的范围 - 如果在函数外部存储和访问引用,它们是否有效?
- 模板签名解析为 void(void) 被 GCC 拒绝;这是否有效C++?
- 我如何知道作为参数的size_t在函数中是否有效?
- 是否可以在C++中获取 CHAR 的有效十六进制地址?
- 我的运算符重载是否有效<<(流插入)左操作数不是 ostream
- C++ 返回指向函数内定义的静态数组的指针是否有效?
- 模板变量是否允许在多个翻译单元中并有效合并?
- 错误:在尝试检测 std::cout 是否<< t 时,功能强制转换为数组类型;有效
- 声明后,gcc 的动态大小数组是否与标准数组有效相同?
- 此递归模板类型定义是否有效C++?
- 将 C 函数转换为 C++ 以检查数字是否有效
- 函数参数的名称与调用函数时使用的变量相同是否有效?
- 如何检查输入是否有效?
- 如何检查用户的输入是否有效以及我正在寻找的数字?
- 堆分配对于大型块中的分页是否更有效?
- 在函数中按值传递 unordered_map/unordered_set 是否有效? C++
- 如何检查isupper(cstr)是否有效?