Overloaded operator << outputs bool value. why?

拟墨画扇 提交于 2020-01-06 19:36:35

问题


xml_attribute.h

#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;
}

The output from the driver is a '1' but I want it to be an '=' sign.
Why is it outputting the reference to a?
If I change XML_AttributeT a(); to XML_AttributeT a; it doesn't even compile.

What did I do wrong?


回答1:


chris is correct. Your initial issue is that XML_AttributeT a() is interpreted as a function declaration. clang++ will actually warn you of this:

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

You can use a{} instead to fix this.

At this point you get a new error:

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;

This is because of what jogojapan said. Your implemented operator<< is using XML_AttributeT const as the attribute type instead of XML_AttributeT const &. If you fix that, then it compiles and gives you the result you want.



来源:https://stackoverflow.com/questions/12487393/overloaded-operator-outputs-bool-value-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!