細かい説明は後にすることにして、まずはその文字連結方法をお見せします↓
#define _CRT_SECURE_NO_DEPRECATE
#include "connect.h"
int main(){
int inum = 2525;
float fnum = 2525;
double dnum = 2525.2525;
printf(cnct()
using namespace std;
#ifndef _FTOS_
#define _FTOS_
string ftos(double num){
char media[33];
sprintf(media, "%f", num);
string str = media;
return str;
}
#endif
#ifndef _ITOS_
#define _ITOS_
string itos(int val, int radix = 10){
char recep[33];
string output = _itoa(val, recep, radix);
return output;
}
#endif
#ifndef _CONNECT_
#define _CONNECT_
class forCNCTclass{
string mystr;
public:
string & content(){ return mystr; }
forCNCTclass & operator<< (int rnum){
mystr.append(itos(rnum) );
return *this;
}
forCNCTclass & operator<< (double rnum){
mystr.append(ftos(rnum) );
return *this;
}
forCNCTclass & operator<< (string &str){
mystr.append(str);
return *this;
}
forCNCTclass & operator<< (const char *str){
mystr.append(str);
return *this;
}
forCNCTclass & operator<< (forCNCTclass &fcc){
mystr.append(fcc.content() );
return *this;
}
const char * operator<<= (int rnum){
mystr.append(itos(rnum) );
return mystr.c_str();
}
const char * operator<<= (double rnum){
mystr.append(ftos(rnum) );
return mystr.c_str();
}
const char * operator<<= (string &str){
mystr.append(str);
return mystr.c_str();
}
const char * operator<<= (const char *str){
mystr.append(str);
return mystr.c_str();
}
const char * operator<<= (forCNCTclass &fcc){
mystr.append(fcc.content() );
return mystr.c_str();
}
const char * operator< (int rnum){
mystr.append(itos(rnum) );
return mystr.c_str();
}
const char * operator< (double rnum){
mystr.append(ftos(rnum) );
return mystr.c_str();
}
const char * operator< (string &str){
mystr.append(str);
return mystr.c_str();
}
const char * operator< (const char *str){
mystr.append(str);
return mystr.c_str();
}
const char * operator< (forCNCTclass &fcc){
mystr.append(fcc.content() );
return mystr.c_str();
}
};
forCNCTclass cnct(){
forCNCTclass fcc;
return fcc;
}
#endif
cnct()関数はforCNCTclassオブジェクトを返しているだけです。実は、そこがミソなのです。
printf(forCNCTclass fcc << inum << fnum);
単純に考えると、上記のように書きたい所ですが、これではコンパイルエラーになってしまいます。
しかし、関数から返ってきたオブジェクトであれば全く問題ありません。
これにより、非常に美しい文字連結が可能になりました。
使用方法詳細
cnct()関数を呼べば、後は<<演算子を使ってどんどん文字・数値(int,double,string&,const char*)を連結してゆけます。最後の連結のときだけ<<=演算子又は<演算子(動作は全く同じですのでお好みの方をご使用ください)を使用することでconst char*型が返され、めでたく連結された文字列を渡すことができます。
以上です。
ここまで興奮して書いたのですが、もしかしたらもう既にこのシステムは発見されているかもしれませんねぇ・・・。