首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

怎样让一个string成员自动编号解决方案

2012-04-01 
怎样让一个string成员自动编号TICPP的一道题目我用stringstream做出来了,就是如果C/C++ codess Bird #

怎样让一个string成员自动编号
TICPP的一道题目
我用stringstream做出来了,就是如果

C/C++ code
ss << "Bird #" <<Bird::i; //注意,Bird和#中间有一个空格ss >> name;

name就只有Bird了,不能够自动编号了。
请问怎么办,还有啥别的方法吗?
/*
14. Write a class called Bird that contains a string member
and a static int. In the default constructor, use the int to
automatically generate an identifier that you build in the
string, along with the name of the class (Bird #1, Bird #2,
etc.). Add an operator<< for ostreams to print out the
Bird objects. Write an assignment operator= and a copyconstructor.
In main( ), verify that everything works
correctly.
*/
C/C++ code
 
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

class Bird {
string name;
static int i;
public:
Bird(){
Bird::i++;
stringstream ss;
ss < < "Bird#" < <Bird::i;
ss >> name;
}
Bird(const Bird& obj) {
Bird::i++;
name = "copyed from " + obj.name;
}
friend ostream& operator < <(ostream& os, const Bird& obj) {
os < < obj.name;
return os;
}
const Bird operator=(const Bird& obj) {
Bird::i++;
name = "assigned from " + obj.name;
return *this;
}
};

int Bird::i = 0;

int main() {
Bird o1;
cout < < o1 < < endl;
Bird o2;
cout < < o2 < < endl;
o2 = o1;
cout < < o2 < < endl;
Bird o3(o2);
cout < < o3 < < endl;
}


[解决办法]
for(int x=0;x<1000;x++){
char sz[32]={0};
sprintf("Bird #%d",i);
cout<<sz;
}
[解决办法]
C/C++ code
Bird(){        Bird::i++;        stringstream ss;        ss << "Bird#" <<Bird::i;        name=ss.str();    } 

热点排行