在某些代码中得到了这个序列。希望将函数调用中的c样式转换转换为c ++样式转换。
char* messageBuffer{ nullptr };
const unsigned long size{ FORMAT_MESSAGE(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
0,
errorMessageID,
MAKELANGID(LANG_NEUTRAL | SUBLANG_DEFAULT),
(char*)&messageBuffer, // this the one want to change
0,
0
)};
由于
编辑:为了清晰起见添加了winapi标记
答案 0 :(得分:2)
代码如下:
Scanner kbd = new Scanner (System.in);
System.out.println("Please enter asset number: ");
assetNum = kbd.nextInt();
System.out.println("Please enter initial purchase price: ");
purchPrice = kbd.nextDouble();
System.out.println("Please enter useful life of the asset (in years): ");
usefulLife = kbd.nextDouble();
System.out.println("Please enter the salvage value: ");
salvageVal = kbd.nextDouble();
System.out.println("Please enter the number of years of depreciation: ");
numYears = kbd.nextDouble();
ddRate = ((1.0 / usefulLife) * 2) * 100;
System.out.println("Asset No: " + assetNum);
System.out.printf("Initial Purchase Price: $%,.0f%n" , purchPrice);
System.out.printf("Useful Life: %.0f years%n" , usefulLife);
System.out.printf("Salvage Value: $%,.0f%n" , salvageVal);
System.out.printf("Double Declining Rate: %.0f%%%n" , ddRate);
System.out.printf("Number of Years: %.0f years%n" , numYears);
System.out.println();
System.out.println("Year Yearly Accumulated Book");
System.out.println(" Depreciation Depreciation Value");
System.out.println();
int year;
double yearlyDepr;
double accDepr;
double bookVal;
bookVal = purchPrice;
accDepr = 0;
year = 0;
while (bookVal >= salvageVal){
yearlyDepr = bookVal * (ddRate / 100);
accDepr = accDepr + yearlyDepr;
bookVal = bookVal - yearlyDepr;
year++;
System.out.printf("%d %,18.0f %,18.0f %,18.0f%n" , year, yearlyDepr, accDepr, bookVal);
}
}
如果有任何读者想知道,是的,带有标记reinterpret_cast<char *>(&messageBuffer)
的Windows API函数FormatMessageA确实指定了这种用法。
请注意,如果正在使用FORMAT_MESSAGE_ALLOCATE_BUFFER
,则转化为FormatMessageW
。我们无法分辨,因为您隐藏了此宏wchar_t *
背后的函数名称。
如果您使用普通文本宏进行Windows API编程,则可以使用:
FORMAT_MESSAGE
并且可能还应将reinterpret_cast<LPTSTR>(&messageBuffer)
声明为messageBuffer
或void *messageBuffer;
。
答案 1 :(得分:1)
策略通常是有原因的,并且使用C ++强制转换而不是C强制转换有两个原因。
如果您只是在那里拍了reinterpret_cast
以符合公司政策,那么第1号大多不在窗外。
我个人会保留C版本,因为当设置某个标志时,API需要它投射到那里但是我也会尝试使其类型安全并且尽可能严格地使用
(LPTSTR)const_cast<LPTSTR*>(&messageBuffer)
但是如果策略没有余地,那么你可以完全使用C ++
reinterpret_cast<LPTSTR>(const_cast<LPTSTR*>(&messageBuffer))