[小小測試] C/C++ 與 Java、struct 與 class 用法比較
附錄:
C 的 struct
#include <stdio.h> #include <stdlib.h> typedef struct { int len; int width; }Rectangle; int main() { Rectangle r1; r1.len=5; r1.width=10; printf("Len=%d\n", r1.len); printf("Width=%d\n", r1.width); printf("Area=%d\n", r1.len*r1.width); // system("pause"); return 0; }
執行結果:
Len=5 Width=10 Area=50
C++ 的 struct
#include <iostream> #include <stdlib.h> using namespace std; typedef struct { int len; int width; }Rectangle; int main() { Rectangle r1; r1.len=5; r1.width=10; cout << "Len=\t" << r1.len << '\n'; cout << "Width=\t" << r1.width << '\n'; cout << "Area=\t" << r1.len*r1.width << '\n'; // system("pause"); return 0; }
執行結果:
Len=5 Width=10 Area=50
Java 的 Class
package jClass; public class Rectangle { public int len; public int width; public int area() { return len * width; } }
主程式
package jClass; public class jClass { public static void main(String[] arg) { Rectangle r1 = new Rectangle(); r1.len=5; r1.width=10; System.out.println("Len=\t" + r1.len); System.out.println("Width=\t" + r1.width); System.out.println("Area=\t" + r1.area()); } }
執行結果:
Len=5 Width=10 Area=50
咦~ C++ 的 class 呢?別急,馬上就來!
C++ 的 class
#include <iostream> #include <stdlib.h> using namespace std; class Rectangle { public: int len; int width; int area() { return len*width; } }; /// <==這裡的';'絕對不能忘記; int main() { Rectangle r1; r1.len=5; r1.width=10; cout << "Len=\t" << r1.len << '\n'; cout << "Width=\t" << r1.width << '\n'; cout << "Area=\t" << r1.area() << '\n'; //system("pause"); return 0; }
執行結果:
Len=5 Width=10 Area=50
參考資料:
What are POD types in C++? – StackOverflow
Creating an instance of class – StakOverflow
When should you use a class vs a struct in C++? – StackOverflow
C/C++ Struct vs Class – StackOverflow
How do you implement a class in C? – StackOverflow
C++ Class access modifiers – TutorialsPoint
Ya~ Facebook 登入成功!