1.C++类的构造函数和析构函数,可以写在外面:
#include <iostream> using namespace std; class String{ char *str; int Num[20]; int Count; public: String(char *s); ~String(); void Process(); void Show(); }; String::String(char *s) { if(s){ str= new char [strlen(s)+1]; str= strcpy(str,s); }else{ str = 0; } Count = 0; } String::~String() { delete [] str; } void String::Process() { int i=0,n; char *p= str; while (*p){ while(*p>='0'&&*p<'9'&&*p){ n=n*10+(*p-'a'); p++; } Num[i++]=n; } Count = i; }
2.C++的可以换行写,不影响编译:
#include <iostream> using namespace std; int main(){ int a[15]={1,2,3,4,5,6,7, 8,9,0,1,2,3 //这么写没毛病 ,4,5}; for (int i=0;i<15;i++){ cout<<a[i]<<endl; } //一句话的代码建议这么写,考试时候看起来方便,括号不至于太多 return 0; }
3.重载函数的类外实现
#include <iostream> using namespace std; class Complex{ float Real,Image; public: Complex(){Real=0;Image=0;} Complex(float r,float i){Real=r; Image=i;} void Print(){ cout<<Real; if(Image>0){cout<<"+";} if(Image!=0){cout<<Image<<"i";} cout<<endl; } Complex operator=(Complex c){ Real = c.Real; Image = c.Image; return *this; } Complex operator,(Complex c); }; Complex Complex::operator,(Complex c){ Complex t; t.Real = Real; t.Image = Image; return t; } int main(){ Complex c1(3.4,5.6),c2(10.5,-12.3),c3; c1.Print(); c2.Print(); c3=(c1,c2); c3.Print(); return 0; }
4.字符串输出问题:
#include <iostream> using namespace std; int main(){ char s[]="Rep\0ch"; int m=sizeof(s); cout<<"m="<<m<<endl; cout<<"输出字符串:"<<endl; for (int i=0;i<sizeof(s);i++){ cout<<s[i]<<endl; } return 0; }
输出的结果是:
m=7
输出字符串:
R
e
p
♦️
c
h
♦️
Process finished with exit code 0