谁能告诉我析构函数在此代码中做什么?通话示例:“
int year = 2012;
string hello = "Hello";
cout << format("% world! The year is %\n") << hello << year;
“我不知道使用“ while”来构造一个析构函数的想法……我们为什么需要它?这应该打印出来:“你好,世界!年份是2012年。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
TempFormat format(const char*) {
return TempFormat(const char*);
}
class TempFormat {
const char* str;
public:
TempFormat(const char* str) : str(str) {}
friend Format& operator<<(ostream& os, TempFormat& f) {
return Format(f.str, os);
}
};
class Format {
const char* str;
ostream& os;
public:
Format(const char* str, ostream& os) : str(str), os(os) {}
template<class T>
Format& operator<<(const T& t) {
while(*str && *str != '%'){
os << *str;
str++;
}
if (*str != '%') {
throw std::exception();
}
os << t;
while(*str && *str != '%'){
os << *str;
str++;
}
return *this;
}
~Format() {
while(*str && *str != '%'){
os << *str;
str++;
}
if (*str == '%') {
throw std::exception();
}
}
};
析构函数仅检查格式字符串中的所有“%”是否都已处理。如果字符串包含的“%”多于对象接收到的参数,则析构函数将引发异常。
编辑:该行cout << format("% world! The year is %\n") << hello << year;
是非常弯曲的,因为<<
这里的运算符都不是经典ostream& operator<<(ostream&, type)
重载。
<<
实际上是Format& operator<<(ostream&, TempFormat&)
,它返回一个Format对象。这也是可憎的,它通过引用返回局部变量,并通过非恒定引用采用无名的临时变量。它甚至可以编译吗?它的原型可能应该Format operator<<(ostream&, TempFormat const&)
改为。但是如果没有返回值优化(或一个好的move构造函数),它将抛出。Format
的插入运算符。Format& Format::operator<<(const T&)
string
Format
的插入操作符。Format& Format::operator<<(const T&)
int
由于该Format
对象是临时对象,因此在operator<<
两次调用之后,该对象在行尾被销毁。而且由于它只包含两个'%',因此它的析构函数不会抛出异常。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句