tôi đang cố gắng để làm việc trên hành quá tải, tập tin tiêu đề của tôi bao gồm:tham khảo Không xác định để điều hành >>
#ifndef PHONENUMBER_H
#define PHONENUMBER_H
#include<iostream>
#include<string>
using namespace std;
class Phonenumber
{
friend ostream &operator << (ostream&, const Phonenumber &);
friend istream &operator >> (istream&, Phonenumber &);
private:
string areaCode;
string exchange;
string line;
};
#endif // PHONENUMBER_H
Và lớp định nghĩa của
//overload stream insertion and extraction operators
//for class Phonenumber
#include <iomanip>
#include "Phonenumber.h"
using namespace std;
//overloades stram insertion operator cannot be a member function
// if we would like to invoke it with
//cout<<somePhonenumber
ostream &operator << (ostream &output, const Phonenumber &number)
{
output<<"("<<number.areaCode<<")"
<<number.exchange<<"-"<<number.line;
return output;
}//end function opertaor <<
istream &operator >> (istream &input, Phonenumber &number)
{
input.ignore(); //skip (
input>>setw(3)>>number.areaCode;//input areacode
input.ignore(2);//skip) and space
input>>setw(3)>>number.exchange;//input exchange
input.ignore();//skip -
input>>setw(4)>>number.line;//input line
return input;
}
gọi điện thoại thực hiện thông qua chính là
#include <iostream>
#include"Phonenumber.h"
using namespace std;
int main()
{
Phonenumber phone;
cout<<"Enter 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<< phone invokes operator << by implicitly issuing the non-member function call operator>>(cout,phone)
cout << phone<<endl;
return 0;
}
nhưng biên dịch điều này cho tôi thấy lỗi trình biên dịch: undefined reference to 'operator>>(std:istream&, Phonenumber&)'
Ai đó có thể giúp tôi giải quyết lỗi này
tôi nhìn thấy một 'istraem' trong định nghĩa của các nhà điều hành input stream. Nhưng nó chỉ là một lỗi đánh máy, phải không? –
Bạn có định nghĩa toán tử mặt bên trái không? Nó sẽ không chỉ gọi toán tử này nếu bạn viết 'phonenumberObj << ostrObj'? Edit: Nevermind, bằng cách nào đó đã bỏ lỡ cuộc tranh luận thứ hai ^^ – Paranaix
Một số người sẽ bảo bạn đừng bao giờ sử dụng 'using namespace std;'. Tôi sẽ không đi xa như vậy, tôi nghĩ rằng nó không sao miễn là bạn giới hạn phạm vi của nó. Nhưng tôi nghĩ * mọi người * sẽ đồng ý rằng bạn không nên đặt nó trong không gian tên chung trong một tiêu đề. –