Win8探索学习笔记(5)WinRT之语法扩展

参考:

http://msdn.microsoft.com/en-us/library/windows/apps/hh454076(v=VS.110).aspx


(1)WinRT对象和引用计数

WinRT是一个OO的库,所以都是以对象的形式操作。在WinRT中,使用引用计数管理对象,关键字ref new新建一个对象,返回的是对象的指针,但是在WinRT中,使用^符号替代*,仍然使用->操作符使用对象的成员方法。另外,由于使用引用计数,不需要使用delete去释放,对象会在最后一个引用失效的时候自动被释放。

说明:WinRT内部是使用COM实现的,对于引用计数,在底层,WinRT对象是一个使用智能指针管理的COM对象。

Platform::String^ str1 = "str1";
Platform::String^ str2 = str1;
Platform::String^ str3 = ref new Platform::String(L"str3");
注意:这里的str1,是对象的“指针”,和std::string的使用不一样。


(2)WinRT中的数字类型

bool    b    = true;
char    c8   = 'A';
char16  c16  = L'A';                // same as wchar_t
int8    i8   = 0x12;                // same as char
int16   i16  = 0x1234;              // same as short
int32   i32  = 0x12345678;          // same as int, long
int64   i64  = 0x1234567890abcdef;  // same as long long, __int64
int8    ui8  = 0x12;                // same as unsigned char
int16   ui16 = 0x1234;              // same as unsigned short
int32   ui32 = 0x12345678;          // same as unsigned int, unsigned long
int64   ui64 = 0x1234567890abcdef;  // same as unsigned long long, __uint64
float32 f32 = 12.34E-23;            // same as float
float64 f64 = 1234.56E-234;         // same as double, long double
C++的数字类型会被自动转换为WinRT对应的类型,比如从一个标准的C++函数返回一个数字值,赋值给winRT类型。

说明:这些类型都定义在Platform命名空间中。


(3)ref class实现自定义类

用ref class标记一个自定义类,就可以使用winRT的对象的方式使用这个类了。当然,在类中,是可以混合使用标准C++的一些类型的。


(4)Value struct结构体

如果一个类只包含数据成员,那么就可以使用value struct定义:

value struct Coordinates
{
  float64 Latitude;
  float64 Longitude;
};

value struct City
{
  Platform::String^ Name;
  int64 Population;
  int Altitude;
  Coordinates Coordinates;
};

(5)WinRT中的property

在WinRT中,使用property关键字声明共有数据成员,而且,还可以为property设置访问它的时候get()、set()的逻辑。

ref class Prescription
{
private:
  Platform::String doctor_;
  int quantity_;
public:
  property Platform::String Name;
  property Platform::String Doctor
  {
    Platform::String get() { return doctor_; }
  }
  property int Quantity
  {
    int get() { return quantity_; }
    void set(int value)
    {
      if (value <= 0) { throw ref new Platform::InvalidArgumentException(); }
      quantity_ = value;
    }
  }
}

(6)WinRT定义接口

WinRT也能实现类似于标准C++的接口功能,当然,标准C++本身并没有提供接口这一概念(很多新的语言如c#、java都有提供),但是标准C++使用纯虚类是可以实现这一功能的。WinRT使用interface关键字来定义一个类为接口类(只需要声明方法,而不需要实现的类),然后就可以被其它的ref class去继承和实现接口了。


(7)WinRT委托、事件、partial类等

WinRT还有一些其他的语法扩展,委托、事件等,发现这些扩展都跟C#一样了,所以不继续废话了。直接看参考链接吧。

PS:以为会有一些特别的地方,发现都是C#的旧东西了。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值