【发布时间】:2021-07-02 19:19:35
【问题描述】:
我对 C++ 比较陌生,并且遇到过使用 ostringstream oss 作为在输出中包含变量并将其设置为字符串的一种方式。
例如
string getDate(){
oss << _month << "," << _day << "," << _year ; //date format
string date = oss.str(); //date as a string
return date;
}
我的问题是,每次我通过一个对象调用 getDate() 方法时,它都会将之前记录的输出添加到我认为所谓的“流”中。
例如
//private variables w default values
int _day{-1};
int _month{-2};
int _year{-3};
int main() {
//init objects
Bday nothing{};
Bday Clyde (12,24,1993);
Bday Harry("Harry",11,05,2002);
//outputs
//expected to return default values (-2,-1,-3)
cout << "Default Values: "<< nothing.getDate() << endl;
//expected to return Clyde's date only: 12,24,1993
cout << "Date Only: " << Clyde.getDate() << endl;
// expect to return Harry's date: (11,05,2002)
cout << "Harry's Bday: " << Harry.getDate() << endl;
return 0;
}
但是输出如下:
Default Values:
Date Only: -2,-1,-3
Harry's Bday: -2,-1,-312,24,1993
Process finished with exit code 0
有什么方法可以保护 oss 的价值,或者至少让它得到更新而不是添加到其中?
【问题讨论】: