0

この課題について少し助けが必要です。文字列を操作するには、演算子を再定義する必要があります。==演算子から始めて、ヘッダーファイルで宣言していますが、cppファイルで関数を定義しようとすると、宣言された関数と互換性がないと表示されます。それはおそらくばかげた間違いです、私は時々これを理解していません。

string.hヘッダーファイル

    #pragma once

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

    #define NOT_FOUND -1

   // C++ String class that encapsulates an ASCII C-string
class String
{
 public:
// Default constructor
String();

// MUST HAVE: Copy-constructor that performs deep copy
String(const String& source);

// Init-constructor to initialize this String with a C-string
String(const char* text);

// Init constructor, allocates this String to hold the size characters
String(int size);

// Destructor
~String();

bool& compareTo(const String& cmp1);
// Assignment operator to perform deep copy
String& operator = (const String& source);

// Assignment operator to assign a C-string to this String
String& operator = (const char* text);

// Returns a reference to a single character from this String
char& operator [] (int index) const;

// Comparison operators
bool operator == (const String& compareTo) const;

string.cppファイル

    #include "string.h"
#include <string>
#include <sstream>

using namespace std;

// Default constructor
String::String()
{
Text = NULL;
}

// MUST HAVE: Copy-constructor that performs deep copy
String::String(const String& source)
{
Text = NULL;
// Call the assignment operator to perform deep copy
*this = source;
}

// Init-constructor to initialize this String with a C-string
String::String(const char* text)
{
Text = NULL;
// Call the assignment operator to perform deep copy
*this = text;
}

// Init constructor, allocates this String to hold the size characters
String::String(int size)
{
Text = new char[size];
}

// Destructor
String::~String()
{
delete[] Text;
}

// Assignment operator to perform deep copy
String& String::operator = (const String& source)
{  
// Call the other assigment operator to perform deep copy
*this = source.Text;
return *this;
}

// Assignment operator to assign a C-string to this String
String& String::operator = (const char* text)
{
// Ddispose of old Text
delete[] Text;

// +1 accounts for NULL-terminator
int trueLength = GetLength(text) + 1;

// Dynamically allocate characters on heap
Text = new char[trueLength];

// Copy all characters from source to Text; +1 accounts for NULL-terminator
for ( int i = 0; i < trueLength; i++ )
    Text[i] = text[i];

return *this;
}

***bool& String::operator ==(string cmp2)***
{
};
4

1 に答える 1

2

あなたのcompareTo宣言にはconstconstがありませんが、定義にはconstがあります。つまり、定義には宣言とは異なる署名があります。

bool& compareTo(const String& cmp1);
                ^^^
bool& String::compareTo(string cmp2)
{
};

ところで、なぜあなたはcompareTo戻ってくるのbool&ですか?

using namespace std;また、ヘッダーファイルでは避ける必要があります。why-is-using-namespace-std-considered-a-bad-practice-in-cを参照してください

于 2013-02-13T00:15:38.157 に答える