【Coding】C++诡异问题之一

来源:互联网 发布:java void是什么意思 编辑:程序博客网 时间:2024/05/20 17:24

代码1:

#include <stdio.h>#include <iostream>using namespace std;class node{public:node();~node();private:int num;node* next;};int main(){//runtiem error//node* p1 = new node;//runtime error//node* p2 = new node();//runtiem error//node n1;node n2();return 0;}

解决上面的问题很容易,只要把构造函数和析构函数实现了就行。

代码2:

#include <stdio.h>#include <iostream>using namespace std;class node{public:node(){cout << (counter++) << endl;}~node(){};private:static int counter;int num;node* next;};int node::counter = 1;int main(){cout << "p1:";node* p1 = new node;cout << "p2:";node* p2 = new node();cout << "n1:";node n1;cout << "n2:";node n2();return 0;}
输出:
p1:1p2:2n1:3n2:
这样我们可以发现为什么代码1中最后一条语句不报错了,它其实是一句函数声明

从代码1和代码2中得到一个体会和两个问题:

体会是在类的声明中写构造函数和析构函数的时候需要实现。

问题是1.node n1;这句语句是变量的声明还是定义,是在定义的时候就初始化了?2.node* p1 = new node;和node* p2 = new node();这两句语句有什么不同?


原创粉丝点击