📄 fig4_3.cpp
字号:
//fig4_3.cpp
//测试类String的程序
#include <iostream.h>
#include "string2.h"
main()
{
String s1("happy"), s2("birthday"), s3(" ");
//测试重载的相等运算符和关系运算符
cout<<"s1 is \""<<s1<<"\"; s2 is \""<<s2<<"\"; s3 is empty \n"
<<"The results of comparing s2 and s1:"
<<"\ns2==s1 yields"<<(s2==s1)
<<"\ns2!=s1 yields"<<(s2!=s1)
<<"\n s2>s1 yields"<<(s2>s1)
<<"\ns 2<s1 yields"<<(s2<s1)
<<"\ns2>=s1 yields"<<(s2>=s1)
<<"\ns2<=s1 yields"<<(s2<=s1)<<"\n\n";
//测试重载运算符!(改运算符用来测试对象是否为空)
cout<<"Testing!s3: \n";
if(!s3){
cout<<"s3 is empty; assigning s1 to s3; \n";
s3=s1; //测试重载的赋值运算符
cout<<"s3 is \""<<s3<<"\"\n\n";
}
//测试重载的连接运算符
cout<<"s1+=s2 yields";
s1+=s2; //测试重载的连接运算符
cout<<"s1="<<s1<<"\n\n";
//测试转换构造函数
cout<<"s1+=\"to you\"yields\n";
s1+="to you"; //测试转换构造函数
cout<<"s1="<<s1<<"\n\n";
//测试用于子串的重载的函数调用运算符()
cout<<"The substring of s1 starting at \n"
<<"location 0 for 14 characters, s1(0, 14), is:"
<<s1(0, 14)<<"\n\n";
//测试到子串尾的子串
cout<<"The substring of s1 starting at \n"
<<"location 15, s1(15, 0) is:"
<<s1(15, 0)<<"\n\n"; //0意味着串尾
//测试拷贝构造函数
String *s4Ptr=new String(s1);
cout<<"*s4Ptr="<<*s4Ptr<<"\n\n";
//测试自我赋值时的赋值运算符=
cout<<"assigning *s4Ptr to *s4Ptr\n";
*s4Ptr=*s4Ptr; //测试自我赋值
cout<<"*s4Ptr="<<*s4Ptr<<endl;
//测试析构函数
delete s4Ptr;
//测试用下标运算符建立左值
s1[0]='H';
s1[6]='B';
cout<<"\ns1 after s1[0]='H' and s1[6]='B' is:"
<<s1<<"\n\n";
//测试下标是否越界
cout<<"Attempt to assign 'd' to s1[30] yields: \n";
s1[30]='d'; //错误:下标越界
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -