C++類模板詳解
如果說類是對象的抽象,對象是類的實例,則類模板是類的抽象,類是類模板的實例
IUnknown介面所提供的IUnknown::QueryInterface(),IUnknown::AddRef()及IUnknown::Release()三個方法的由來。所有的COM元件都要實作IUnknown,Invoke()方法,另外為了跨語言的支援,GetIDsOfNames()的原因,將這些方法組合起IDispatch介面,所有實作此介面的,都可以支援跨語言的支援。/** * 假設People有variable age,其值限定於0到130之間 */ public class People { private int age; public People(int d) { this.age = d; } public int getAge() { return age; } public void setAge(int d) { if (d >= 0 && d <= 130) { // 檢查年齡是否合法 age = d; } } public void increaseAge() { if (age < 130) { // 檢查年齡是否合法 this.age++; } } public static void main(String[] argv) { People e1, e2; // e1,e2 are references to Object People, not the Object themselves e1 = new People(3); e2 = new People(5); e1.setAge(30); e2.setAge(50); e1.increaseAge(); e2.increaseAge(); } }this這個keyword表示接收到此訊息的物件。由於設計時是定義Class, 而執行時則是Object接受訊息, Class只有一個, 但Object可以有很多個, 因此必須使用this表達現在接收到此訊息的物件。
public class ErrorCall { int data; // object variable public void objectMethod() { data = 10; } public static void classMethod() { objectMethod(); // Compile Error data = 10; // Compile Error } }