[英]Why does this call to sprintf_s() work, and how can I make this work on my computer?
[英]How to make a class work as string for printf_s / sprintf_s?
我正在嘗試創建一個類,假設MyClass在以下條件下工作:
MyClass name = "everyone"; // Assigns "everyone" into a local string variable.
printf_s("Hello %s!", name); // Should output "Hello everyone!" without the quotes.
我試過重載運算符const char *()以及運算符char *(),但似乎都沒有成功。
如果使用operator const char*
重載它,則可以顯式轉換它:
MyClass name = "everyone";
printf_s("Hello %s!", (const char*)name);
// prints "Hello everyone!"
然后它將正常運行。 如果printf
在第一個參數之后可以接受任何類型的參數,則它不能隱式工作,因此編譯器不知道將其強制轉換為什么樣的參數。
當然,這假定您的類的operator const char*
返回everyone
的C樣式字符串。
正如Tomalak Geret'kal在評論中指出的那樣,使您的類隱式可轉換為const char*
可能會導致很多問題,因為它可以在不知道/不需要的情況下進行自身轉換。
正如Kerrek SB所指出的那樣,使類與printf
兼容可能不值得,因為畢竟這是C ++。 最好為ostream&
s編寫一個operator<<
重載樣式:
ostream& operator<<(ostream& rhs, const MyClass& c) {
rhs << c.name; // assuming the argument to the constructor
// is stored in the member variable name
return rhs;
}
MyClass name = "everyone";
cout << "Hello " << name << '!';
// prints "Hello everyone!"
當傳遞給省略號(...)時,您無法“檢測”到轉換為char const *的意圖。 您的對象將被放在堆棧上,並且可能會崩潰。 這與將對象傳遞到顯式采用char const*
,在這種情況下,可以觸發隱式轉換運算符。
我建議使用與標准庫相同的方法,並盡可能少地使用隱式轉換。 而是使用c_str()
成員之類的東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.