2012-07-04 2 views
2

For 루프는 std :: vector를 반복하고 내용을 채워야합니다. 루프의 첫 번째C++ 객체의 벡터를 반복하고 콘솔에 내용을 표시하는 방법

는 말을 나에게 오류 메시지를 제공합니다 :

NO 이항 연산자가 < < 없음 가능한 변환 FOUND

vector<MyClass>classVector; 
    for (vector<MyClass>::iterator i = classVector.begin(); 
          i != classVector.end(); 
          ++i) 
      { 
       cout << *i << endl; 
      } 

에서 MyClass.h :

루프 반복을위한
class MyClass{ 

private: 

    string newTodayTaskString; 

public: 
    MyClass(string t) : newTodayTaskString (t){} 

    ~MyClass(){} 
}; 

이를 통해 문자열의 벡터와 완벽하게 작동합니다. 왜?

vector<string>stringVector; 
    for (vector<string>::iterator i = stringVector.begin(); 
         i != stringVector.end(); 
         ++i) 
      { 
       cout<<*i<<endl; 
      } 

답변

3

당신은 당신이 직접 std::cout::operator <<를 호출 할 수 있도록하려는 경우 클래스의 스트림 연산자를 오버로드해야합니다.

당신은로 정의 할 수 있습니다 :

std::ostream& operator << (std::ostream& stream, const MyClass& obj) 
{ 
    stream << obj.newTodayTaskString; 
} 

하고 클래스의 private 멤버에 액세스 할 수 있도록 친구로이 연산자를 선언하거나 클래스 대신 사용하는 인쇄 기능을 제공합니다.

1

클래스 자체가 아닌 클래스 멤버를 인쇄하려고한다고 생각합니다. 예를 들어

:

cout << (*i).Name << endl; 
+0

혼동스러워서 죄송합니다. –

5

문제는 operator <<를 오버로드하는 방법에 대한 How to properly overload the << operator for an ostream?를 참조하면

std::string s = "Hello"; 
std::cout << s; 

하지만

MyClass o("Hello"); 
std::cout << o;  

을 작성할 수 있습니다 단지 그것 때문에, 반복 관련이 그것을 작동하게!

0

출력 연산자를 오버로드해야합니다.

#include <iostream> 
#include <string> 
#include <vector> 
#include <iterator> 

class MyClass{ 

private: 
    std::string newTodayTaskString; 

public: 
    explicit MyClass(const std::string t) : newTodayTaskString (t){} 
    std::ostream& print(std::ostream& os) const { return os << newTodayTaskString; } 

    ~MyClass(){} 
}; 

std::ostream& operator << (std::ostream& os, const MyClass& obj) 
{ 
    return obj.print(os); 
} 

int main() 
{ 
    std::vector<MyClass> vec = {MyClass("add"), MyClass("clear")}; 
    std::copy(vec.begin(), vec.end(), std::ostream_iterator<MyClass>(std::cout, "\n")); 
} 
+0

솔루션을 제공해 주셔서 감사합니다. –

0

당신은 아마도 아래는 사용자 정의에 관심이 "MyClass에"클래스의 어떤 데이터에 컴파일러를 말해야 당신 type.So. 이다 "MyClass에"의 벡터를 통해 반복된다 이해를 돕기위한 샘플 코드 -

// Temp_Practice.cpp : Defines the entry point for the console application. 
// 

#include "stdafx.h" 
#include<iostream> 
#include<memory> 
#include<ostream> 
#include <vector>> 
using namespace std; 

// This example is just for understanding/Demo purpose. 
// it will not run on any compiler 
class MyClass { 
public: 
    std::string _name; 
    std::string _address; 
    int   _age; 
    // Constructor 
public: 
    MyClass() {} 
    MyClass(std::string name, std::string address, int age) :_name(name), _address(address), _age(age) {} 

    //Destructor 
    //.. 

    // other stuff 
    friend ostream& operator << (ostream& os, std::string _input); 

}; 
ostream& operator << (ostream& os, std::string _input) 
{ 
    os << _input.c_str(); 
    return os; 
} 

int main() 
{ 
    std::vector<MyClass> vecMyClass; 

    MyClass temp("AA", "BB", 1); 
    vecMyClass.push_back(temp); 

    MyClass temp1("CC", "DD", 2); 
    vecMyClass.push_back(temp1); 

    MyClass temp2("EE", "FF", 3); 
    vecMyClass.push_back(temp2); 

    MyClass temp3("GG", "HH", 4); 
    vecMyClass.push_back(temp3); 

    MyClass temp4("II", "JJ", 5); 
    vecMyClass.push_back(temp4); 

    MyClass temp5("KK", "LL", 6); 
    vecMyClass.push_back(temp5); 
    std::vector<MyClass>::iterator itr; 
    for (itr = vecMyClass.begin(); itr != vecMyClass.end(); ++itr) 
    { 
     // Compiler throws error; it does not know what programer wants to print. So its 
     // programer responsiblity to let compiler know what to be printed 
     //std::cout << itr << std::endl; // Error!!!! 

     // Correct Code 
     std::cout << itr->_name << itr->_address << itr->_age << std::endl; 
    } 
    return 0; 
} 
관련 문제