Ich studiere C++ mit Deitels Buch. Ich versuche, Beispiel für das Überladen von Operatoren zu erstellen, aber es schlägt fehl. Kannst du mir erklären warum? Hier ist der Code:keine Übereinstimmung für Operator <<
Klasse-Prototypen:
// PhoneNumber class definition
#include <iostream>
#include <string>
#ifndef PHONENUMBER_H
#define PHONENUMBER_H
class PhoneNumber
{ // Start class PhoneNumber
friend std::ostream & operator<<(std::ostream &output, const PhoneNumber &number);
friend std::istream & operator>>(std::istream &input, PhoneNumber &number);
private:
// 3-digit area code
std::string areaCode;
// 3-digit exchange
std::string exchange;
// 4-digit line
std::string line;
}; // End Class PhoneNumber
#endif // PHONENUMBER_H
Klassendefinition:
// Overloaded stream insertion and stream extraction operators
// for class PhoneNumber
#include <iomanip>
#include "phonenumber.h"
using namespace std;
// overloaded stream insertion operator; can't be
// a member function if we would like to invoke it with
// cout << somePhoneNumber;
ostream & operator <<(ostream &output, const PhoneNumber &number)
{ // Start operator<<()
output << "(" << number.areaCode << ") " << number.exchange < "-" << number.line;
return output; // enables cout << a << b << c;
} // End operator<<()
// overloaded stream extraction operator; can't be
// a member function if we would like to invoke it with
// cin >> somePhoneNumber
istream & operator >>(istream &input, PhoneNumber &number)
{ // Start operator>>()
// skip (
input.ignore();
// input area code
input >> setw(3) >> number.areaCode;
// skip) and space
input.ignore(2);
// input exchange
input >> setw(3) >> number.exchange;
// skip dash(-)
input.ignore();
// input line
input >> setw(4) >> number.line;
return input; // enables cin >> a >> b >> c;
} // end operator>>()
Testfunktion:
// Demonstrating class PhoneNumber's overloaded stream insertion
// and stream extraction operators
#include <iostream>
#include "phonenumber.h"
using namespace std;
int main(int argc, char *argv[])
{
PhoneNumber phone; // create object phone
cout << "Enter phone number in the form (123) 456-7890:" << endl;
// cin >> phone invokes operator>> by implicitly issuing
// the non-member function call operator>>(cin, phone)
cin >> phone;
cout << "The phone number entered was: ";
// cout << phone invokes operator<< by implicitly issuing
// the non-member function call operator<<(cout, phone)
cout << phone << endl;
return 0;
}
Wenn ich versuche, es zu bauen Ich erhalte eine Fehlermeldung :
phonenumber.cpp:13: error: no match for ‘operator<<’ (operand types are ‘const char [2]’ and ‘const string {aka const std::__cxx11::basic_string<char>}’)
output << "(" << number.areaCode << ") " << number.exchange < "-" << number.line;
Können Sie mir bitte erklären, was ist der Grund für den Fehler?
Ihre Betreiber gibt es nur in der CPP-Datei. Sie benötigen eine Deklaration in der .h, so dass Ihr Haupt weiß darüber. –