0

xml_attribute.h오버로드 된 연산자 << 출력 bool 값. 왜?

#pragma once 
#ifndef XML_ATTRIBUTET_H 
#define XML_ATTRIBUTET_H 

#include <string> 
#include <iostream> 

struct XML_AttributeT{ 

    std::string tag; 
    std::string value; 

    //constructors 
    explicit XML_AttributeT(std::string const& tag, std::string const& value); 
    explicit XML_AttributeT(void); 

    //overloaded extraction operator 
    friend std::ostream& operator << (std::ostream &out, XML_AttributeT const& attribute); 
}; 
#endif 

xml_attribute.cpp

#include "xml_attribute.h" 

//Constructors 
XML_AttributeT::XML_AttributeT(std::string const& tag_, std::string const& value_) 
: tag{tag_} 
, value{value_} 
{} 
XML_AttributeT::XML_AttributeT(void){} 

//overloaded extraction operator 
std::ostream& operator << (std::ostream &out, XML_AttributeT const attribute){ 
    return out << attribute.tag << "=" << attribute.value; 
} 

driver.cpp

#include <iostream> 
#include <cstdlib> 
#include "xml_attribute.h" 

int main(){ 
    using namespace std; 

    XML_AttributeT a(); 
    cout << a << endl; 

    return EXIT_SUCCESS; 
} 

드라이버의 출력은 '1'하지만 그것은 '는 되길 = '표시.
참조를 출력하는 이유는 무엇입니까?
XML_AttributeT a();에서 XML_AttributeT a;으로 변경하면 컴파일되지 않습니다.

내가 뭘 잘못 했니?

+3

아, 가장 번거로운 구문 분석. C++ 11을 사용하고 있기 때문에'()'대신'{}'을 사용하여 초기화를 통일 할 수 있습니다. – chris

+5

'operator <<'의 두 번째 인수는'XML_AttributeT const' (즉 값으로 전달)로 선언되지만 friend 선언은 XML_AttributeT const & (참조로 전달)를 사용합니다. 그들은 동일해야합니다 (나는 참조로 통과하는 것이 좋습니다). – jogojapan

+0

@jogojapan 우, 좋은 눈. 결정된. –

답변

5

크리스가 맞습니다. 처음 문제는 XML_AttributeT a()이 함수 선언으로 해석된다는 것입니다. clang++ 사실이 당신을 경고합니다 : 당신은이 문제를 해결하는 대신 a{}을 사용할 수 있습니다

Untitled.cpp:33:21: warning: empty parentheses interpreted as a function declaration [-Wvexing-parse] 
    XML_AttributeT a(); 

.

Untitled.cpp:34:10: error: use of overloaded operator '<<' is ambiguous (with operand types 'ostream' (aka 'basic_ostream<char>') and 'XML_AttributeT') 
    cout << a << endl; 

이 때문에 말을 jogojapan이다 :이 시점에서

당신은 새로운 오류가 발생합니다. 구현 된 operator<<XML_AttributeT const & 대신 속성 유형으로 XML_AttributeT const을 사용하고 있습니다. 문제를 해결하면 컴파일되어 원하는 결과를 얻을 수 있습니다.

+2

FWIW는 GCC (-Waddress)를 사용하여 출력하려고하면 * XML_AttributeT의 주소가 항상 *로 평가 될 것이라는 경고를받습니다. 이는 매우 큰 오류는 아니지만 올바른 방향의 한 단계입니다. . – chris