การใช้งาน Preprocessor directive
preprocessor directive จะขึ้นต้นด้วย # แล้วตามด้วยชื่อ
โดย preprocessor directive ใน C++/CLI ได้แก่
#using
#pragma
#if
#ifdef
#elif
#else
#endif
#error
#line
#include
#undef
#define
ตัวอย่าง
#include "stdafx.h"
using namespace System;
#define A 65 //กำหนด preprocessor directive
#define B 66
void main(){
int a = A;
int b =B;
Console::WriteLine("a = {0}, b = {1}",a,b);
Console::ReadLine();
}
ตัวอย่าง
#include "stdafx.h"
using namespace System;
#define I 10//กำหนด preprocessor directive
#define J 20
#define SUM (I)*(J)
void main(){
Console::WriteLine(SUM); //จะได้ผลลัพธ์เป็น 200
Console::ReadLine();
}
การใช้ directive แบบเงื่อนไข
รูปแบบ
#if (เงื่อนไข)
//คำสั่ง
#elif (เงื่อนไข)
//คำสั่ง
#else
//คำสั่ง
#endif
ตัวอย่าง
#include "stdafx.h"
using namespace System;
#define I 10
#define J 20
void main(){
#if (I < J)
Console::WriteLine("I<J");
#else
Console::WriteLIne("I>J");
#endif
Console::ReadLine();
}
การใช้งาน include
include ทำหน้าที่นำไฟล์จากที่อื่นมาใช้ในการใช้ include จะมีรูปแบบสองอย่างคือ
#include <ไฟล์>
#include "ไฟล์"
เช่น
#include "stdafx.h"
การใช้งาน Template
template เหมือนกับฟังก์ชั้นสำหรับกำหนดส่วนต่างๆเพื่อให้เรียกใช้งาน
รูปแบบ
template <class T>
T template_name (parameter){
//คำสั่ง
}
ตัวอย่าง
#include "stdafx.h"
using namespace System;
template <class T>
T Sum (T a,T b){
return (a+b);
}
void main(){
int a = 11;
int b = 12;
Console::WriteLine(Sum(a,b));
Console::ReadLine();
}
ในกรณีที่เราต้องการกำหนด template สำหรับข้อมูลชนิดต่างๆมากกว่า 1 ชนิดก็เขียนได้ดังนี้
template <class T1,class T2>
การใช้งาน คลาส template
#include "stdafx.h"
using namespace System;
template <class T>
ref class Test{
public:
Test();
Test(T x,T y);
T X;
T Y;
static Test^ operator +(const Test^ i,const Test^ j);
static Test^ operator -(const Test^ i,const Test^ j);
virtual String^ ToString() override;
};
template <class T>
Test<T>::Test() : X((T)1),Y((T)1){}
template <class T>
Test<T>::Test(T x,T y):X(x),Y(y) {}
template <class T>
Test<T>^ Test<T>::operator +(const Test^ i,const Test^ j){
Test^ t =gcnew Test();
t->X=i->X+j->X;
t->Y=i->Y+j->Y;
return t;
}
template <class T>
Test<T>^ Test<T>::operator -(const Test^ i,const Test^ j){
Test^ t =gcnew Test();
t->X=i->X*j->X;
t->Y =i->Y*j->Y;
return t;
}
template <class T>
String^ Test<T>::ToString(){
return String::Format("x = {0} , y = {1}",X,Y);
}
void main(){
Test<int>^ t = gcnew Test<int>(3,5);
Test<int>^ u = gcnew Test<int>(4,7);
Test<int>^ s = u-t;
Console::WriteLine(s);
}
การใช้ Generic
รูปแบบ
generic <class T>
การใช้งาน typedef
typedef ทำหน้าที่กำหนดข้อมูลใหม่
ตัวอย่าง
#include "stdafx.h"
using namespace System;
void main(){
typedef array<int> i;
i^ x = gcnew i(3);
x[0]=1;
x[1]=2;
x[2]=3;
i^ y = gcnew i(5);
y[0] = 10;
y[1] = 20;
y[2] = 30;
y[3] = 40;
y[4] = 50;
for each(int xx in x){
Console::WriteLine(xx);
}
for each(int yy in y){
Console::WriteLine(yy);
}
Console::ReadLine();
}
[With great power comes great responsibility]