有趣的重载:
#include <stdio.h>
const char endl = '\n';
class Console
{
public:
Console& operator << (int i)
{
printf("%d", i);
return *this;
}
Console& operator << (char c)
{
printf("%c", c);
return *this;
}
Console& operator << (const char* s)
{
printf("%s", s);
return *this;
}
Console& operator << (double d)
{
printf("%f", d);
return *this;
}
};
Console cout;
int main()
{
cout << 1 << endl;//想要连续传送,就必须写么写:
cout << "D.T.Software" << endl;//Console& operator << (int i)
//不能是void operator << (int i)
double a = 0.1;
double b = 0.2;
cout << a + b << endl;
return 0;
}
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
using namespace std;
int main()
{
printf("Hello world!\n");
char* p = (char*)malloc(16);
strcpy(p, "D.T.Software");
double a = 3;
double b = 4;
double c = sqrt(a * a + b * b);
printf("c = %f\n", c);
free(p);
return 0;
}
小结1
C语言中没有真正意义上的字符串,只有字符数组
#include <iostream>
#include <string>
using namespace std;
void string_sort(string a[], int len)
{
for(int i=0; i<len; i++)
{
for(int j=i; j<len; j++)
{
if( a[i] > a[j] )
{
swap(a[i], a[j]);
}
}
}
}
string string_add(string a[], int len)
{
string ret = "";
for(int i=0; i<len; i++)
{
ret += a[i] + "; ";
}
return ret;
}
int main()
{
string sa[7] =
{
"Hello World",
"D.T.Software",
"C#",
"Java",
"C++",
"Python",
"TypeScript"
};
string_sort(sa, 7);
for(int i=0; i<7; i++)
{
cout << sa[i] << endl;
}
cout << endl;
cout << string_add(sa, 7) << endl;
return 0;
}
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
#define TO_NUMBER(s, n) (istringstream(s) >> n)
#define TO_STRING(n) (((ostringstream&)(ostringstream() << n)).str())
int main()
{
double n = 0;
if( TO_NUMBER("234.567", n) )
{
cout << n << endl;
}
string s = TO_STRING(12345);
cout << s << endl;
return 0;
}
#include <iostream>
#include <string>
using namespace std;
string operator >> (const string& s, unsigned int n)
{
string ret = "";
unsigned int pos = 0;
n = n % s.length();
pos = s.length() - n;
ret = s.substr(pos);
ret += s.substr(0, pos);
return ret;
}
int main()
{
string s = "abcdefg";
string r = (s >> 3);
cout << r << endl;
return 0;
}
右移一位思路: