| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 949 人关注过本帖
标题:设计一个字符串类MyString的问题。程序不知道怎么改
只看楼主 加入收藏
mosquiyan
Rank: 1
等 级:新手上路
帖 子:22
专家分:0
注 册:2014-12-12
结帖率:85.71%
收藏
 问题点数:0 回复次数:0 
设计一个字符串类MyString的问题。程序不知道怎么改
/*设计一个字符串类MyString,使其只有1个私有成员:char *str(指向字符串的指针);
该类具有构造函数、析构函数、复制构造函数,且具有其他成员函数:(参照教材p232页)
a.求取该字符串的长度;
b.可以让两个MyString对象进行拼接;如abc, bcd 拼接成abcbcd
c.比较两个字符串的大小;
d.在指定位置插入另一个字符串;
等等。。。
该类所具有的功能越全越好;要求不能使用系统提供的功能函数:如strlen等,只能调用自己完成的功能函数。*/

#include <iostream>
#include <string>
using namespace std;

class MyString
{
    public:
        MyString();//默认构造函数
        MyString(const char *s);//用指针s所指向的字符串常量初始化类的对象。构造函数
        MyString(const MyString &rhs);//复制构造函数
        
        unsigned int length() const;//返回字符串的长度
        
        void comp (const MyString p1,const MyString p2) const;//比较大小
        
        void add(const MyString p1,const MyString p2);//将字符串拼接
        
        
        ~MyString(){}
    private:
        const char *str;              
};

MyString::MyString(const char *s)
{
    s=" ";
    str=s;
}//构造函数的实现,这个函数应该写得不对,但是不知道怎么改

MyString::MyString( const MyString &rhs)
{
    str=rhs.str;
} //复制构造函数的实现

unsigned int MyString::length() const
{
    int n=0;
    while(*(str+n)!='\0')
       n++;
    return n;
} //输出字符串的长度 */

void  MyString::comp(const MyString p1,const MyString p2) const
{
    if(p1.str==p2.str)
      cout<<"p1=p2."<<endl;
      
    if(p1.str>p2.str)
      cout<<"p1>p2."<<endl;
      
    if(p1.str<p2.str)
      cout<<"p1<p2."<<endl;     
}//比较两个字符串的大小

void MyString::add(const MyString p1,const MyString p2)
{
    cout<<(p1.str+p2.str);
}//连接两个字符串*/

int main()
{
    MyString myp1("123"),myp2("happy");
    cout<<"The length of myp1 and myp2:"<<endl;
    cout<<myp1.length()<<" "<<myp2.length()<<endl;
   
    cout<<"Compare myp1 with myp2:"<<endl;
    (myp1,myp2);
   
    cout<<"Add myp2 to myp1:"<<endl;
    myp1.add;
   
    return 0;
}
想问一下大家以上的程序哪里出错了?还有string append(const char *s);int compare(const string &str) const;这些函数是怎么运用的?可以给一个运用实例我看看吗?
搜索更多相关主题的帖子: include 字符串 拼接 
2015-04-21 16:37
快速回复:设计一个字符串类MyString的问题。程序不知道怎么改
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.014028 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved