C++-我的字符串类的重载运算符&> [英] C++ - overloading operator >> for my string class

查看:80
本文介绍了C++-我的字符串类的重载运算符&>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实现了字符串类MyString。以下是代码:

#include <iostream>
#include <cstring>

using std::cout;
using std::endl;

class MyString{
    private:
    char * content;
    int length;
    void copy(const MyString & source);
    public:
    MyString();
    MyString(const char * source);
    ~MyString();
    MyString(const MyString & source);
    void print(void);
    MyString & operator = (const MyString &source);
    friend std::ostream & operator << (std::ostream & out, const MyString&   towrite);
    friend std::istream & operator >> (std::istream & in, MyString & toread);
};

MyString::MyString(){
    content = new char[1];
    content[0] = '';
    length = 0;
}


MyString::MyString(const char *source){
    length = strlen(source);
    content = new char[length + 1];
    strcpy(content, source);
}

MyString::~MyString(){
    delete[] content;
}

void MyString::copy(const MyString & source){
    length = source.length;
    content = new char[length + 1];
    strcpy(content, source.content);
}

MyString::MyString(const MyString & source){
    copy(source);
}

void MyString::print(void){
    cout << "" << content << endl;
}

MyString &MyString::operator=(const MyString &source){
    copy(source);
    return *this;
}

std::ostream & operator<<(std::ostream & out,const MyString& towrite){
    out << towrite.content;
    return out;
}

std::istream & operator >> (std::istream & in, MyString & toread){
    int length;
    std::cout << "Enter length of word: " << endl;
    std::cin >> length;
    toread.length = length;
    toread.content = new char[toread.length+1];
    for (int i = 0; i < toread.length; i++){
    in >> toread.content[i] ;
    }
    toread.content[toread.length] = '';
    return in;
 }

我的问题与重载运算符有关>>。

对于此主程序:

int main(){
    MyString word;
    std::cout<<"Enter some word: "<<endl;
    std::cin>>word;
    std::cout<<"Your entered: "<<word<<endl;
}

这是输出:

Enter some word:

Enter length of word:

5

stack

Your entered: stack

Process returned 0 (0x0)   execution time : 8.313 s

Press any key to continue.
它会正确打印用户输入的字符串,但不会按照我想要的方式"模拟"原始的字符串类。以下是原因。

如果使用C++字符串类:

int main(){
    std::string word;
    std::cout<<"Enter some word: "<<endl;
    std::cin>>word;
    std::cout<<"Your entered: "<<word<<endl;
}

用户不需要输入单词长度。我可以用我的班级实现这一点吗?

EDIT1:

我是这样做的:

std::istream & operator >> (std::istream & in, MyString & toread){
    char *temp;
    temp = new char[100];
    char c;
    int i = 0;
    while(c != '
'){
    c = getchar();
    temp[i++] = c;
    }
    temp[i] = '';
    int length = i-1;
    toread.length = length;
    toread.content = new char[toread.length+1];
    for(int i = 0 ; i < toread.length ; i++){
    toread.content[i] = temp[i];
    }
    delete [] temp;
    toread.content[toread.length+1]='';
}

它的工作方式是应该的。但是,我收到了警告,因为我没有返回"in":

||=编译:在fdsfsdf中调试(编译器:GNU GCC编译器)=| C:UsershaeDesktopfdsfsdfmain.cpp||in函数‘std::iStream&;OPERATOR>>(std::iStream&;,MyString&;)’:| C:UsershaeDesktopfdsfsdfmain.cpp|137|警告:函数中没有返回非空的语句[-WReturn-type] |=构建完成:0个错误,1个警告(0分4秒)= |=运行:在fdsfsdf中调试(编译器:GNU GCC编译器)=|

推荐答案

这是我很久以前编写的一个类似类的精简版本。这是一件古董,但它应该可以工作,并解决了您的班级的一些问题。

class charray {
public:
    charray();
    ~charray();

    charray(const charray&);
    charray(const char*);

    charray& operator=(const charray&);
    charray& operator=(const char*);

    void swap(charray&);

    const char* c_str() const
    { return m_elem; }

    unsigned int size() const
    { return m_size; }

private:
    void m_resize(unsigned int size);

    char* m_elem;
    unsigned int m_size;
};

// private.
void charray::m_resize(unsigned int size)
{
    char* elem = new char[size+1];

    memcpy(elem, m_elem, std::min(m_size, size));
    elem[size] = '';
    delete [] m_elem;

    m_elem = elem;
    m_size = size;
}

// public.
charray::charray()
    : m_elem(0), m_size(0)
{
    m_resize(0);
}

charray::~charray()
{
    delete [] m_elem;
}

charray::charray(const charray& src)
    : m_elem(0), m_size(0)
{
    unsigned int size = src.size();
    m_resize(size);
    memcpy(m_elem, src.c_str(), size);
}

charray::charray(const char* src)
    : m_elem(0), m_size(0)
{
    unsigned int size = std::strlen(src);
    m_resize(size);
    memcpy(m_elem, src, size);
}

charray& charray::operator=(const charray& rhs)
{
    charray temp(rhs);
    this->swap(temp);
    return *this;
}

charray& charray::operator=(const char* rhs)
{
    charray temp(rhs);
    this->swap(temp);
    return *this;
}

void charray::swap(charray& b)
{ 
    std::swap(m_elem, b.m_elem);
    std::swap(m_size, b.m_size);
}

这可能是您最感兴趣的内容。密切关注细节。在直接处理内存时,正常的实现和中断的实现之间的区别通常非常微妙。

注意:运营商不是朋友。他们不访问私有数据。

std::ostream& operator<<(std::ostream& out, const charray& in)
{
    return out << in.c_str();
}

std::istream& operator>>(std::istream& in, charray& out)
{
    // verify no errors are set, flush tied streams, strip leading
    // whitespace.
    std::istream::sentry sentry(in);
    if (!sentry)
        return in;

    unsigned int size = 0;
    unsigned int tail = 0;
    char* temp = 0;
    int next; // @note int not char (to record EOF).

    while ((next = in.get()) != in.eof() && !std::isspace(next)) {
        // if temp buffer is exhausted, then double the buffer size.
        // (base size of 16).
        if (tail == size) {
            unsigned int newsize = std::max(2*size, 16u);
            char* newtemp = new char[newsize+1];
            memcpy(newtemp, temp, size);
            delete [] temp;
            temp = newtemp;
            size = newsize;
        }
        temp[tail++] = next;
    }
    // @note because the stream is prepeared with istream::sentry, there
    // will be at least one non-whitespace character in the stream.
    assert(temp != 0);
    temp[tail] = '';
    out = temp;
    delete [] temp;
    return in;
}

做完全相同的事情的更简单、更安全的方法

#include <vector>
std::istream& operator>>(std::istream& in, charray& out)
{
    std::istream::sentry sentry(in);
    if (!sentry)
        return in;

    std::vector<char> temp;
    int next;

    while ((next = in.get()) != in.eof() && !std::isspace(next))
        temp.push_back(next);
    temp.push_back('');
    out = &temp[0];
    return in;
}

编辑
以上内容已过时(C++11之前的版本)。现代实现很可能会以不同的方式处理构造和分配。以下是这些方法的更新版本

注意:方法m_resize已不存在。所有内容都通过构造函数进行处理。

charray::charray(const char* src, unsigned int size)
    : m_elem{ new char[size+1]{} }, m_size{ size }
{
    std::copy(src, src + size, m_elem);
}

charray::charray()
    : charray(nullptr, 0)
{}

charray::charray(const charray& src)
    : charray(src.m_elem, src.m_size)
{}

charray::charray(const char* src)
    : charray(src, std::strlen(src))
{}

charray::charray(charray&& src)
    : m_elem{ src.m_elem }, m_size{ src.m_size }
{
    src.m_elem = nullptr;
    src.m_size = 0;
}

// handle both move and copy assignment.
charray& charray::operator=(charray rhs)
{
    this->swap(rhs);
    return *this;
}

希望这能有所帮助。祝你好运。

这篇关于C++-我的字符串类的重载运算符&>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆