string类
class String
{
public:
String(const char* cstr=0);
String(const String& str);
String& operator=(const String& str);
~String();
char* get_c_str() const { return m_data; }
private:
char* m_data;
};
inline
String::String(const char* cstr)
{
if (cstr) {
m_data = new char[strlen(cstr)+1];
strcpy(m_data, cstr);
}
else {
m_data = new char[1];
*m_data = '\0';
}
}
inline
String::~String()
{
delete[] m_data;
}
ostream& operator<<(ostream& os, const String& str)
{
os << str.get_c_str();
return os;
}
静态函数&静态变量
class Account {
public:
static double m_rate;
static void set_rate(const double& x) { m_rate = x; }
};
double Account::m_rate = 8.0;
int main()
{
Account::set_rate(5.0);
Account a;
a.set_rate(7.0);
}
类模板
template<typename T>
class complex
{
public:
complex(T r, T i = 0):re(r), im(i)
{}
T real() const { return re; }
T imag() const { return im; }
int func(const complex& param)
{
return param.im + param.re;
}
complex& operator += (const complex& r)
{
return _doapl(this, r);
}
private:
T re, im;
//返回值为complex不是void,为了防止c3 += c2 += c1不能执行
friend complex& _doapl(complex* ths, const complex& r)
{
ths->re += r.re;
ths->im += r.im;
return *ths;
}
};
//返回ostream的os类型,是为了连续输出 cout<<c1<<conj(c1);
//不能是void类型,void类型满足单次输出
//ostream& operator << (ostream& os, const complex& x)
//{
// return os << "(" << x.real() << "+" << x.imag() << 'i'
// << ")";
//}
//ostream& operator << (ostream& os, const complex& x)
//{
// return os << "(" << x.real() << "+" << x.imag() << 'i'
// << ")";
//}
int main()
{
complex<double> c1(2, 5);
complex<int> c2(6);
cout << c2.real() << " +i" << c2.imag() << endl;
cout << endl;
return 0;
}