C++高手请进,用printf输出一个对象的问题一道C++笔试题,它定义了一个类如下:class word{char str[20]publ
C++高手请进,用printf输出一个对象的问题
一道C++笔试题,它定义了一个类如下:
class word{
char str[20];
public:
word(){strcpy(str, "hello !");}
};
这个类未补全,要求在public里补全,使下面的main函数正确输出:
int main()
{
word w;
map<string, word> m;
map<string, word>::iterator itr;
m.insert(pair<string, word>("111", w));
itr=m.begin();
printf("%s\n", itr->second); //主要是这句
return 0;
}
求大神解答!
[解决办法]
在只改动类的情况下,这样可以
- C/C++ code
/* * main.cpp * * Created on: 2012-9-21 * Author: yss-tan-198 */#include <map>#include <string>#include <utility>#include <cstdio>using namespace std;class word { char str[20];public: word() {strcpy(str, "hello !");} // C++中函数推演,特殊函数比通用函数printf(const char *, ... )更合适这一特性 friend void printf(const char *fmt, word w){ printf(fmt, w.str); }};// 这个类未补全,要求在public里补全,使下面的main函数正确输出:int main(){ word w; map<string, word> m; map<string, word>::iterator itr; m.insert(pair<string, word>("111", w)); itr=m.begin(); printf("%s\n", itr->second); //主要是这句 return 0;} 