2009-10-13 6 views
1

operator <<에 어떻게 오버로드 할 수 있습니까? 오버로드 된 연산자의 목적은 cout << ptr->info이며 메모리 주소는 수신하지 않고 해당 노드 정보 섹션의 제조업체 연도와 모델을 표시합니다.운영자 과부하 << 연결된 목록에 있음

예 : 노드의 각 정보 섹션에서

template <class DataType> 
struct Node { 
DataType info; 
Node<DataType> *next; 
}; 

이 같은 구조체가있을 것입니다 :

struct Car { 
    string maker; 
    string year; 
    string model; 
} 

지금까지 내가 이것을 가지고 있지만 작동하는 것 같다하지 않습니다

:
friend ostream &operator << (ostream &output, Node<DataType> &rlist) { //Overloaded << 
    output << rlist->info.make << endl; 
    output << rlist->info.year << endl; 
    output << rlist->info.price << endl; 

    return output; 
} 

내가 g 컴파일 ++ 나는이 오류

+0

@Jacob는, 적어도 우리가 같은 태그 편집 한 결투 : – GManNickG

+0

이 것은 약 2보다 편집에 커뮤니티 위키를 끝낼 것 ... –

+0

@GMan : 나는 운영자 오버로드 : – Jacob

답변

1

LinkedList.cpp: In member function ‘void LinkedList<DataType>::EscribaUltimo() [with DataType = CarType]’: 
main.cpp:37: instantiated from here 
LinkedList.cpp:15: error: no match for ‘operator<<’ in ‘std::cout << ptr->Node<CarType>::info’ 
그냥 확인, 당신이 바로, 운영자의 정의 전에

template<class DataType> 

이 만드는? 내가 그렇게하면, 그것은 나를 위해 일한다. 오류 메시지는 코드의 행 번호를 표시하지만 붙여 넣은 정의의 어디에 있습니까? 그것을 읽고, 나는 문제가에 대해 정의 된 연산자 < <을 가지고 있지 않는

Node<DataType> myNode; 
output << myNode 

으로 만

output << myNode.info 

하지라고 생각합니다.

편집 : 귀하의 의견에 의해 자동차에 < < 연산자를 정의하려는 것으로 들립니다. 그래서,

ostream& operator<< (ostream& output, Car& car) { 
    output << car.foo << end; 
    output << car.bar << end; 
    return output; 
} 

template <class DataType> 
ostream& operator<< (ostream& output, Node<DataType>& node) { 
    output << node.info << end; 
    return output; 
} 

기본적으로 (검증되지 않은) 할 것, 어떤 것을 의미하는 것은 당신이 당신의 노드 유형을 전문으로하고 그 위에 < < 연산자를 사용하고자 할 때, 당신은 데이터 형식이 전문으로하고 있는지 확인해야한다는 것입니다 또한 < < 연산자가 정의되어 있습니다. 노드 하나 (또는 ​​Node*), 및 차량에 대한 하나 :

+0

I myNode.info에 대한 연산자 <<를 정의하는 방법을 모른다. 그것이 바로 내가하고 싶은 일입니다. –

+0

Car에 대한 액세스 오류에 대한 Naveen (정확한) 발언과 주어진 연산자가 기껏해야 Car에 대한 템플릿의 특수화라는 점을 감안하면, 그것이 놀랍다는 것을 알게되었습니다. 실제로 출력을 얻었습니까? 아니면 컴파일 만 했습니까? –

+0

Martin, 거기에 무슨 일이 있을까요? 주요 기능조차 없다. 제가 의미하는 바는 Loki가 제공 한 코드를 취하고 작업과 비슷한 것을 얻었습니다. 정확하지 않은 것에 대해 유감입니다. – bsdfish

0

당신은 두 개의 연산자를 필요

ostream &operator << (ostream &output, Car &car) { 
    output << car.maker << endl; 
    output << car.year << endl; 
    output << car.model << endl; 
    return output; 
} 

template<class DataType> 
ostream &operator << (ostream &output, Node<DataType> *rlist) { 
    output << rlist->info; 
    return output; 
} 
2

당신이 실제 주요 코드가 누락이기 때문에 나는 조금 혼란 스러워요 있지만. 나는 링크를 통과에서 당신이 노드를 가정하는 것, 그리고 지금을 인쇄 할거야 :

#include <iostream> 
#include <string> 

using namespace std; // not recommended, but useful 
        // in snippets 

// T is usually used, but this is of course up to you 
template <class T> 
struct Node 
{ 
    typedef T value_type; // a usual typedef 

    value_type info; 
    Node<value_type> *next; 
}; 

struct Car 
{ 
    string maker; 
    string year; 
    string model; 
}; // you had a missing ;, probably copy-paste error 

// this creates a node. normally you'd want this to be 
// wrapped into a list class (more on this later) 
template <typename T> 
Node<T> *createNode(const T& info = T()) 
{ 
    // allocate node 
    Node<T> *result = new Node<T>; 
    result->info = info; 
    result->next = 0; // no next 

    return result; // returning a pointer means 
        // whoever gets this is 
        // responsible for deleting it! 
} 

// this is the output function for a node 
template <typename T> 
std::ostream& operator<<(std::ostream& sink, const Node<T>& node) 
{ 
    // note that we cannot assume what node contains! 
    // rather, stream the info attached to the node 
    // to the ostream: 
    sink << node.info; 

    return sink; 
} 

// this is the output function for a car 
std::ostream& operator<<(std::ostream& sink, const Car& car) 
{ 
    // print out car info 
    sink << "Make: " << car.maker << 
      "\nYear: " << car.year << 
      "\nModel: " << car.model << std::endl; 

    return sink; 
} 

int main(void) 
{ 
    // a car list 
    typedef Node<Car> CarList; 

    // a couple cars 
    Car car1 = {"Dodge", "2001", "Stratus"}; 
    Car car2 = {"GMan's Awesome Car Company", "The future", "The best"}; 

    CarList *head = createNode(car1); // create the first node 
    head->next = createNode(car2); 

    // now traverse the list 
    CarList *iter = head; 
    for (; iter != 0; iter = iter->next) 
    { 
     // output, dereference iterator to get the actual node 
     std::cout << "Car: " << *iter << std::endl; 
    } 

    // dont forget to delete! 
    iter = head; 
    while (iter) 
    { 
     // store next 
     CarList *next = iter->next; 

     // delete and move on 
     delete iter; 
     iter = next; 
    } 
} 

을 지금 당신은 당신의 자신의 연결리스트를 만들 수없는 경우, 표준 링크 목록을 사용하여 대신 작업을 대폭 간소화합니다.

#include <algorithm> 
#include <iostream> 
#include <iterator> 
#include <list> 
#include <string> 

using namespace std; 

struct Car 
{ 
    string maker; 
    string year; 
    string model; 
}; 


// this is the output function for a car 
std::ostream& operator<<(std::ostream& sink, const Car& car) 
{ 
    // print out car info 
    sink << "Make: " << car.maker << 
      "\nYear: " << car.year << 
      "\nModel: " << car.model << std::endl; 

    return sink; 
} 

int main(void) 
{ 
    // a car list 
    typedef std::list<Car> CarList; 

    // a couple cars 
    Car car1 = {"Dodge", "2001", "Stratus"}; 
    Car car2 = {"GMan's Awesome Car Company", "The future", "The best"}; 

    CarList cars; 
    cars.push_back(car1); 
    cars.push_back(car2); 

    // now traverse the list (copy to ostream) 
    std::copy(cars.begin(), cars.end(), 
      std::ostream_iterator<Car>(std::cout,"\n")); 

    // delete done automatically in destructor 
} 

희망이 있습니다.

관련 문제