zoukankan      html  css  js  c++  java
  • 【Coding】C++诡异问题之一

    代码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:1
    p2:2
    n1:3
    n2:
    
    这样我们可以发现为什么代码1中最后一条语句不报错了,它其实是一句函数声明

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

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

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


  • 相关阅读:
    149. Max Points on a Line(js)
    148. Sort List(js)
    147. Insertion Sort List(js)
    146. LRU Cache(js)
    145. Binary Tree Postorder Traversal(js)
    144. Binary Tree Preorder Traversal(js)
    143. Reorder List(js)
    142. Linked List Cycle II(js)
    141. Linked List Cycle(js)
    140. Word Break II(js)
  • 原文地址:https://www.cnblogs.com/haoaina521/p/3332096.html
Copyright © 2011-2022 走看看