2 回答
TA贡献1786条经验 获得超13个赞
我还加了一个>>重载 #include#includeusing namespace std;/*每个成员函数都是只归对象使用的,当一个对象调用成员时,这里面的成员只归该对象所有,只有该对象可以修改*/class String{public: String(); String(char *ch); /*复制构造函数在用 该对象的一个对象初始化另一个对象的时候 需要调用复制构造函数*/ String(const String &); //复制构造函数 ~String(){ cout << "正在执行析构函数!" << endl; } friend ostream &operator << (ostream &out, String &a) { out < a.p; return out; } friend istream &operator >> (istream &in, String &a) { in >> a.p; return in; }private: String(unsigned short int length); int len; char *p;};String::String(){ cout << "调用默认构造函数!" << endl; len = 0; p = new char; *p = '\0';}String::String(char *ch){ cout << "正在执行带一个参数*ch的构造函数" << endl; len = strlen(ch); p = new char[len + 1]; for (int i = 0; i < len; i++) { p[i] = ch[i]; } p[len] = '\0';}String::String(unsigned short int length){ cout << "正在执行带一个参数unsigned short int 的构造函数" << endl; len = length; p = new char[length + 1]; //这里的p是对象str的成员 for (int i = 0; i <= length; i++) p[i] = '\0';}int main(){ String str("美好世界!"); cout << str << endl; return 0;}
TA贡献1806条经验 获得超8个赞
#include <stdio.h>int MyStrcmp(char *p1,char *p2) {
int i = 0;
for(;((p1[i] != '\0') && (p2[i] != '\0'));i++) {
if(p1[i] > p2[i]) return 1;
else if(p1[i] < p2[i]) return -1;
}
if((p1[i] == '\0') && (p2[i] == '\0')) return 0;
if(p1[i] == '\0') return -1;
return 1;
}int main() {
int cmpres;
char s1[50];
char s2[50];
printf("Enter s1 you want to estimate:");
scanf("%s",s1);
printf("Enter s2 you want to estimate:");
scanf("%s",s2);
cmpres = MyStrcmp(s1,s2);
if(cmpres > 0) printf("s1 > s2\n\n");
else if(cmpres == 0) printf("s1 = s2\n\n");
else printf("s1 < s2\n\n");
return 0;
}
添加回答
举报