轉型運算子:)
型別轉換會提供一種方法中的特定狀況的物件型別的明確轉換。
unary-expression
( type-name ) cast-expression
備註
所有一元 (unary) 運算式被視為 cast 運算式。
編譯器會將轉型運算式 為型別 型別名稱在進行型別轉換之後。 轉換 (cast) 可用於任何純量型別的物件或將轉換為從任何其他純量型別。 明確型別轉換 (cast) 都會受到相同規則,判斷的隱含轉換效果。 在 [轉換 (cast) 上的其他限制可能會產生實際的大小或特定類型的表示。
範例
// expre_CastOperator.cpp
// compile with: /EHsc
// Demonstrate cast operator
#include <iostream>
using namespace std;
int main()
{
double x = 3.1;
int i;
cout << "x = " << x << endl;
i = (int)x; // assign i the integer part of x
cout << "i = " << i << endl;
}
// expre_CastOperator2.cpp
// The following sample shows how to define and use a cast operator.
#include <string.h>
#include <stdio.h>
class CountedAnsiString
{
public:
// Assume source is not null terminated
CountedAnsiString(const char *pStr, size_t nSize) :
m_nSize(nSize)
{
m_pStr = new char[sizeOfBuffer];
strncpy_s(m_pStr, sizeOfBuffer, pStr, m_nSize);
memset(&m_pStr[m_nSize], '!', 9); // for demonstration purposes.
}
// Various string-like methods...
const char *GetRawBytes() const
{
return(m_pStr);
}
//
// operator to cast to a const char *
//
operator const char *()
{
m_pStr[m_nSize] = '\0';
return(m_pStr);
}
enum
{
sizeOfBuffer = 20
} size;
private:
char *m_pStr;
const size_t m_nSize;
};
int main()
{
const char *kStr = "Excitinggg";
CountedAnsiString myStr(kStr, 8);
const char *pRaw = myStr.GetRawBytes();
printf_s("RawBytes truncated to 10 chars: %.10s\n", pRaw);
const char *pCast = myStr; // or (const char *)myStr;
printf_s("Casted Bytes: %s\n", pCast);
puts("Note that the cast changed the raw internal string");
printf_s("Raw Bytes after cast: %s\n", pRaw);
}