轉換運算子: ()
類型轉換提供了一個明確的轉換方法,可在特定情況下轉換物件的類型。
語法
cast-expression
:
unary-expression
(
type-name
)
cast-expression
備註
所有一元運算式皆會視為 Cast 運算式。
編譯器在 cast-expression
進行型別轉換之後會被視為類型 type-name
。 轉型可用來將任何純量類型的物件與任何其他純量類型的物件來回轉換。 明確類型轉換受到與判斷隱含轉換效果的相同規則所限制。 轉換的其他限制可能是由特定類型的實際大小或表示所造成。
範例
內建類型之間的標準轉換:
// 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);
}
RawBytes truncated to 10 chars: Exciting!!
Casted Bytes: Exciting
Note that the cast changed the raw internal string
Raw Bytes after cast: Exciting
另請參閱
具有一元運算子的運算式
C++ 內建運算子、優先順序和關聯性
明確類型轉換運算子: ()
轉型運算子 (C++)
轉型運算子 (C)
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應