0

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

ドライバー.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;と、コンパイルさえしません。

私は何を間違えましたか?

4

1 に答える 1

5

クリスは正しいです。最初の問題はXML_AttributeT a()、関数宣言として解釈されることです。clang++実際にこれについて警告します:

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

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 constXML_AttributeT const &

于 2012-09-19T01:38:51.597 に答える