explicit 关键字用于声明必须使用强制转换来调用的用户定义的类型转换运算符
来源:互联网 发布:小户型装修 知乎 编辑:程序博客网 时间:2024/05/16 23:49
explicit 关键字用于声明必须使用强制转换来调用的用户定义的类型转换运算符。例如,在下面的示例中,此运算符将名为 Fahrenheit 的类转换为名为 Celsius 的类:
// Must be defined inside a class called Farenheit:
public static explicit operator Celsius(Farenheit f)
...{
return new Celsius((5.0f/9.0f)*(f.degrees-32));
}
可以如下所示调用此转换运算符:下面的示例提供Farenheit f = new Farenheit(100.0f);
Celsius c = (Celsius)f;
Fahrenheit
和 Celsius
类,它们中的每一个都为另一个提供显式转换运算符。// cs_keyword_explicit_temp.cs
using System;
class Celsius
...{
public Celsius(float temp)
...{
degrees = temp;
}
public static explicit operator Fahrenheit(Celsius c)
...{
return new Fahrenheit((9.0f / 5.0f) * c.degrees + 32);
}
public float Degrees
...{
get ...{ return degrees; }
}
private float degrees;
}
class Fahrenheit
...{
public Fahrenheit(float temp)
...{
degrees = temp;
}
public static explicit operator Celsius(Fahrenheit f)
...{
return new Celsius((5.0f / 9.0f) * (f.degrees - 32));
}
public float Degrees
...{
get ...{ return degrees; }
}
private float degrees;
}
class MainClass
...{
static void Main()
...{
Fahrenheit f = new Fahrenheit(100.0f);
Console.Write("{0} fahrenheit", f.Degrees);
Celsius c = (Celsius)f;
Console.Write(" = {0} celsius", c.Degrees);
Fahrenheit f2 = (Fahrenheit)c;
Console.WriteLine(" = {0} fahrenheit", f2.Degrees);
}
}
using System;
class Celsius
...{
public Celsius(float temp)
...{
degrees = temp;
}
public static explicit operator Fahrenheit(Celsius c)
...{
return new Fahrenheit((9.0f / 5.0f) * c.degrees + 32);
}
public float Degrees
...{
get ...{ return degrees; }
}
private float degrees;
}
class Fahrenheit
...{
public Fahrenheit(float temp)
...{
degrees = temp;
}
public static explicit operator Celsius(Fahrenheit f)
...{
return new Celsius((5.0f / 9.0f) * (f.degrees - 32));
}
public float Degrees
...{
get ...{ return degrees; }
}
private float degrees;
}
class MainClass
...{
static void Main()
...{
Fahrenheit f = new Fahrenheit(100.0f);
Console.Write("{0} fahrenheit", f.Degrees);
Celsius c = (Celsius)f;
Console.Write(" = {0} celsius", c.Degrees);
Fahrenheit f2 = (Fahrenheit)c;
Console.WriteLine(" = {0} fahrenheit", f2.Degrees);
}
}
- explicit 关键字用于声明必须使用强制转换来调用的用户定义的类型转换运算符
- 强制类型转换运算符的优先级
- 区分一下强制类型转换运算符重载/赋值运算符重载/对象定义的赋值
- 用户定义的类型转换
- 隐式转换:用户定义的转换必须是转换成封闭类型,或者从封闭类型转换
- 强制转换类型运算符
- 强制类型转换运算符
- 强制类型转换运算符
- 强制类型转换运算符
- 强制类型转换运算符
- 标准C++的四种强制转换类型运算符
- 【C++】强制类型转换运算符的重载
- C++需要注意的强制类型转换运算符
- C#学习记录 运算符与类型的强制转换
- 强制类型转换和as运算符的区别
- (+=)运算符中隐藏的强制类型转换问题
- 复习试题:运算符以及类型的强制转换
- 隐式类型转换和explicit关键字的作用
- linux内核驱动开发笔试题
- Telnet
- String例子---String--String[]
- HDC,CDC,CClientDC的区别和联系是什么? (转)
- 2006年11月9日 Working with Data and ASP.NET 2.0
- explicit 关键字用于声明必须使用强制转换来调用的用户定义的类型转换运算符
- XX公司招聘C笔试题
- ×××公司linux内核驱动开发招聘笔试题
- 驱动版Hello World
- 编写Linux下的UDP Client/Server程序
- Servlet
- SQL 数据库所有者 (dbo)与数据库角色 db_owner 区别
- slackware 咯血take my life
- sizeof,终极无惑(上)