2016-06-17 2 views
2

과부하, 그것은 가장 감소 프로그램 :오류가 연산자 '>>'내 코드를 확인, >> 연산자를 오버로드하는 것을 시도하고있다

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

class MyClass{ 
private: 
    string bar; 
    int foo; 

public: 
    MyClass(){ 
    bar=""; 
    foo=0; 
}; 

istream& operator>>(istream& is){ 
    is >> bar >> foo; 
    return is; 
}; 

ostream& operator<<(ostream& os){ 
    os << bar << foo; 
    return os; 
}; 

~MyClass(){}; 
}; 

int main() 
{ 
    MyClass* a = new MyClass(); 

    cin >> *a; 

    delete a; 

    return 0; 
} 

이 코드 를 컴파일되지 않습니다, 검색 좀했습니다 내 질문을 게시하기 전에 문제가 가장 귀찮은 구문 일 수 있다는 것을 알았지 만 문제를 해결하는 방법을 상상할 수는 없습니다.

첫째 : 문제입니다

어쨌든, 내가 컴파일 할 때, 컴파일러가 발생, 모르는

다음
error: no match for ‘operator>>’ (operand types are ‘std::istream {aka std::basic_istream<char>}’ and ‘MyClass’) 
cin >> *a; 
~~~~^~~~~ 

, 유형이 int로 변환하는 시도 후, 이중, 문자 등이 발생 :

/usr/include/c++/6.1.1/istream:924:5: nota: candidate: 
std::basic_istream<_CharT, _Traits>& std::operator>>(std::basic_istream<_CharT, _Traits>&&, _Tp&) [con _CharT = char; _Traits = std::char_traits<char>; _Tp = MyClass] <coincidencia cercana> 
operator>>(basic_istream<_CharT, _Traits>&& __is, _Tp& __x) 
^~~~~~~~ 
/usr/include/c++/6.1.1/istream:924:5: nota: conversion of argument 1 would be ill-formed: 
error: no se puede unir el l-valor ‘std::istream {aka std::basic_istream<char>}’ a ‘std::basic_istream<char>&&’ 
cin >> *a; 

나는이 문제를 해결하기 위해 무엇을 할 수 있는가?

+1

누군가 친구가 필요합니다. :-) – paxdiablo

답변

4

멤버 함수로 입력 연산자와 출력 연산자를 오버로드 할 수 없습니다. 그 이유는 사용자가 >> 또는 << 연산자를 멤버 함수로 정의했을 때 클래스의 객체 인스턴스는 왼쪽 왼쪽에 있어야합니다.

대신

class MyClass 
{ 
public: 
    ... 

    friend std::ostream& operator<<(std::ostream& os, MyClass const& object) 
    { 
     return os << object.bar << object.foo; 
    } 
}; 
0

">>"와 같은 (클래스에 인라인으로 행해질 수있다) 이외의 부재 친구 기능과 같은 조작 기능을 정의하는 "< <"연산자는 일반적 멤버 함수로서 구현되지 첫 번째 인수가 멤버 함수에서 해당 클래스의 암시 적 객체이기 때문에 수행 할 수 있지만 main.A. cin과 같은 작업을 수행하는 경우 작동합니다. 다른 연산자는 위에서 설명한 것처럼 전역 함수로 구현합니다. 위의 대답.

관련 문제