Context
最近學習C++,之前也就是大學二級的水平,還自以爲懂了。現在一看,呵呵…
我是Java5年了,感覺和C++的class struct unit實例化差異很大。
Classes
Classes are an expanded concept of data structures: like data structures, they can contain data members, but they can also contain functions as members.
Classes包含
- class
- 默認member(方法、屬性)的可見性爲 private
- struct, unit
- 默認member 的可見性爲 public
Class 實例化
1.
實例化兩個對象rect1, rect2。
class Rectangle {
int width, height;
public:
void set_values (int,int);
int area (void);
} rect1, rect2;
實際和 int a
一樣,type在前 variable name在後
2. constructor
// class_name object_name = initialization_value;
// class_name object_name { value, value, value, ... }
Circle foo (10.0); // functional form
Circle bar = 20.0; // assignment init.
Circle baz {30.0}; // uniform init.
Circle qux = {40.0}; // POD-like
完整代碼
// classes and uniform initialization
#include <iostream>
using namespace std;
class Circle {
double radius;
public:
Circle(double r) { radius = r; }
double circum() {return 2*radius*3.14159265;}
};
int main () {
Circle foo (10.0); // functional form
Circle bar = 20.0; // assignment init.
Circle baz {30.0}; // uniform init.
Circle qux = {40.0}; // POD-like
cout << "foo's circumference: " << foo.circum() << '\n';
return 0;
}
默認構造
Rectangle rectb; // default constructor called
Rectangle rectc(); // function declaration (default constructor NOT called)
Rectangle rectd{}; // default constructor called
3. 動態初始化
Rectangle * prect = new Rectangle (5, 6);
內存分配在heap上,必須顯式的回收內存 delete prect
Tips
如果 objectA在method1()裏創建,在method2()裏調用。
則需要用動態初始化,而不能用2.的初始化。
因爲2的內存在超出method1()就可能被回收了。
實例
int main()
{
BinaryTreeNode rootNode;
rootNode.m_nValue = 2;
BinaryTreeNode *pRootNode = &rootNode;
init(pRootNode);
printTop2Bottom(pRootNode);
// release(pRootNode);
return 0;
}
- 我在init中創建BinaryTree(二叉樹)
- 在printTop2Bottom中遍歷
- 如果init時
BinaryTreeNode* node2
創建節點,node2.value = 2
賦值 - printTop2Bottom中聲明一個 對象
std::deque<BinaryTreeNode *> dequeTreeNode;
- node2.value就會變化(Error)
- 但用
BinaryTreeNode node2 = new BinaryTreeNode()
,就不會有問題
原因就是new是在heap上,BinaryTreeNode* node2
應該類比於Java的方法棧裏的局部內存,所以中printTop2Bottom實例化對象時dequeTreeNode,就把原node2內存重寫了
Java對比
Java是直接沒用 第1、2兩種方式,只有new Class一種方式,這樣確實簡單很多。