Нужна помощь в написании строкового класса - PullRequest
0 голосов
/ 02 мая 2018

Я пишу строковый класс, и я думаю, что мой перегруженный оператор присваивания и конструктор копирования в порядке, так как именно это сказал мне мой инструктор, когда читал слова из файла в вектор строковых классов. Тем не менее, ничего не печатает. Это одна из этих функций, которая является проблемой или что-то еще?

Кроме того, я не понимаю, почему эти два ответственны. Оператор присваивания не используется в fin >> word[wordCount], строка, читающая слова из файла в вектор в main, так как здесь используется оператор присваивания и конструктор копирования?

основной

#include "stdafx.h"
#include <iostream>
#include "MYString12.h"
#include <vector>
#include <cstdlib>
#include <algorithm>
#include <iomanip>


using namespace std;

int main()
{
    vector<MYString12> word(100);

    ifstream fin;

    fin.open("thisfile.txt");

    if (fin.fail()) {
        cout << "Error." << endl;
        exit(1);
    }


    int wordCount = 0;
    while (fin >> word[wordCount]) {
        cout << word[wordCount];
        wordCount++;
    }

    word.resize(wordCount);


    fin.close();

    system("pause");
    return 0;
}

.h

/*Class description:
A string class. Various functions for the class.
String is passed into objects of the class. Reads
and writes to files.*/

#ifndef MYString12_H
#define MYString12_H

#include <fstream>

using namespace std;

class MYString12
{
public:
    MYString12();
    MYString12(const MYString12 & mstr);
    MYString12(const char* ptr);
    ~MYString12();
    MYString12& operator = (const MYString12& mstr);
    friend MYString12 operator + (const MYString12& str1, const MYString12& str2);
    char operator [] (int index);
    bool operator > (const MYString12& argStr2);
    bool operator < (const MYString12& argStr2);
    bool operator == (const MYString12& argStr);
    friend istream& operator >> (istream& istr, MYString12& argStr);
    friend ostream& operator << (ostream& istr, MYString12& argStr);
    int length() const;
    int capacity()const;
    char at(int index);
    const char* c_str()const;
    static int getCurrentCount();
    static int getCreatedCount();

private:
    char* str;
    int cap = 20;
    int end;
    const int compareTo(const MYString12& argStr);
    static int currentCount;
    static int createdCount;
};
#endif

.cpp

#include "stdafx.h"
#include "MYString12.h"
#include <iostream>
#include <iomanip>
#include <math.h>
#include <cstdlib>

using namespace std;

int MYString12::createdCount = 0;
int MYString12::currentCount = 0;

// default constructor
MYString12::MYString12()
{
    cap = 20;
    end = 0;
    str = new char[cap];
    str[end] = '\0';

    createdCount++;
    currentCount++;
}

// copy constructor
MYString12::MYString12(const MYString12& mstr)
{
    this->end = mstr.end;
    this->cap = mstr.cap;
    this->str = new char[mstr.cap];

    while (end >= cap) {
        cap += 20;
    }

    for (int i = 0; i < end; i++) {
        str[i] = mstr.str[i];
    }
    //mstr.str[end] = '\0';

    createdCount++;
    currentCount++;
}


// constructor with string passed in
MYString12::MYString12(const char* ptr)
{
    int i = 0;
    while (ptr[i] != '\0') {
        i++;
    }
    end = i;

    while (end >= cap) {
        cap += 20;
    }

    str = new char[cap];

    for (int j = 0; j < end; j++) {
        str[j] = ptr[j];
    }

    createdCount++;
    currentCount++;
}

// destructor
MYString12::~MYString12()
{
    delete[] str;
    currentCount--;
}

// overloaded assignment operator
MYString12& MYString12::operator = (const MYString12& mstr)
{
    if (this == &mstr) {
        return *this;
    }

    this->end = mstr.end;
    this->cap = mstr.cap;

    while (end >= cap) {
        cap += 20;
    }

    for (int i = 0; i < end; i++) {
        str[i] = mstr.str[i];
    }
    //mstr.str[end] = '\0';

    return *this;
}

// overloaded concatanation operator
MYString12 operator + (const MYString12& str1, const MYString12& str2)
{
    int temp = str1.end + str2.end + 1;

    char tempArray[200];

    int i = 0;
    int j = 0;
    while (i < temp)
    {
        if (i < str1.end)
        {
            tempArray[i] = str1.str[i];
            i++;
        } else {
            tempArray[i] = str2.str[j];
            i++;
            j++;
        }
    }

    tempArray[i] = '\0';

    MYString12 concatenatedObj(tempArray);

    return concatenatedObj;
}

// overloaded index operator
char MYString12::operator [] (int index)
{
    return str[index];
}

// overloaded greater than operator
bool MYString12::operator > (const MYString12& argStr)
{
    if ((*this).compareTo(argStr) > 0)
    {
        return true;
    }
    else {
        return false;
    }
}

// overloaded less than operator
bool MYString12::operator < (const MYString12& argStr)
{
    if ((*this).compareTo(argStr) < 0)
    {
        return true;
    }
    else {
        return false;
    }
}

// overloaded equals equals operator
bool MYString12::operator == (const MYString12& argStr)
{
    if ((*this).compareTo(argStr) == 0)
    {
        return true;
    }
    else {
        return false;
    }
}

// compares ascii values of objStr and argStr
const int MYString12::compareTo(const MYString12& argStr)
{
    int asciiSubtraction = 0;
    int limit = 0;

    if (end <= argStr.end)
    {
        limit = end;
    }
    else {
        limit = argStr.end;
    }

    int i = 0;
    while (i <= limit && (str[i] == argStr.str[i])) {
        i++;
    }

    asciiSubtraction = str[i] - argStr.str[i];

    return asciiSubtraction;
}

// overloaded extraction operator
istream& operator >> (istream& istr, MYString12& argStr)
{
    char temp[100];

    istr >> temp;

    argStr = MYString12(temp);

    return istr;
}

// overloaded insertion operator
ostream& operator << (ostream& ostr, MYString12& argStr)
{
    int i = 0;
    while (argStr.str[i] != '\0')
    {
        ostr << argStr.str;
        i++;
    }
    return ostr;
}

// returns size of passed in string
int MYString12::length() const
{
    return end;
}

// returns size of memory allocated 
int MYString12::capacity() const
{
    return cap;
}

// returns a char of string at passed index
char MYString12::at(int index)
{
    if (index < 0 || index > end) {
        return '\0';
    }
    else {
        return str[index];
    }
}

// returns passed in string as c string
const char* MYString12::c_str() const
{
    createdCount++;
    currentCount++;

    return str;
}

// returns the amount of alive instances of class
int MYString12::getCurrentCount()
{
    return currentCount;
}

// returns the amount of overall created instances of class
int MYString12::getCreatedCount()
{
    return createdCount;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...