Tre*_*key 0 c++ reference operator-overloading most-vexing-parse c++11
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
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
driver.cpp
#include <iostream>
#include <cstdlib>
#include "xml_attribute.h"
int main(){
using namespace std;
XML_AttributeT a();
cout << a << endl;
return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)
驱动程序的输出为'1',但我希望它是'='符号.
为什么输出引用?
如果我XML_AttributeT a();
改为XML_AttributeT a;
它甚至不编译.
我做错了什么?
克里斯是对的.您的初始问题是XML_AttributeT a()
被解释为函数声明.clang++
实际上会警告你:
Untitled.cpp:33:21: warning: empty parentheses interpreted as a function declaration [-Wvexing-parse]
XML_AttributeT a();
Run Code Online (Sandbox Code Playgroud)
您可以使用它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;
Run Code Online (Sandbox Code Playgroud)
这是因为jogojapan所说的.您实现的operator<<
是使用XML_AttributeT const
作为属性类型而不是XML_AttributeT const &
.如果你修复了它,那么它会编译并为你提供你想要的结果.
归档时间: |
|
查看次数: |
223 次 |
最近记录: |