重载操作符<输出bool值。为什么? [英] Overloaded operator << outputs bool value. why?
问题描述
xml_attribute.h
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
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
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;
它甚至不编译。
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.
我做错了什么?
推荐答案
chris是正确的。你最初的问题是 XML_AttributeT a()
被解释为一个函数声明。 clang ++
实际上会警告您:
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();
您可以使用 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;
这是因为jogojapan说的。您实现的运算符<<
正在使用 XML_AttributeT const
作为属性类型,而不是 XML_AttributeT const &
。如果你解决了,那么它会编译并给你你想要的结果。
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.
这篇关于重载操作符<输出bool值。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!