Overloaded operator << outputs bool value. w

2019-08-17 01:50发布

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条回答
时光不老,我们不散
2楼-- · 2019-08-17 02:15

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.

查看更多
登录 后发表回答