我有一个带有重载插入运算符的类,它可在我的驱动程序中工作:

#include <iostream>
#include <cstdlib>
#include "xml_attribute.h"

int main(){
    using namespace std;

    XML_AttributeT a("name","value");
    cout << a << endl;

    return EXIT_SUCCESS;
}


输出:name =“ value”
作品。

我想在包含该类的另一个类中利用此功能:
标头

#pragma once
#ifndef XML_ELEMENTT_H
#define XML_ELEMENTT_H

#include <string>
#include <vector>
#include <iostream>
#include "xml_attribute/xml_attribute.h"

struct XML_ElementT{

    std::string start_tag;
    std::vector<XML_AttributeT> attributes;
    bool single_tag;

    //Constructors
    explicit XML_ElementT(std::string const& start_tag, std::vector<XML_AttributeT> const& attributes, bool const& single_tag);
    explicit XML_ElementT(void);

    //overloaded extraction operator
    friend std::ostream& operator << (std::ostream &out, XML_ElementT const& element);

};
#endif


cpp

#include "xml_element.h"

//Constructors
XML_ElementT::XML_ElementT(std::string const& tag_, std::vector<XML_AttributeT> const& attributes_, bool const& single_tag_)
: start_tag{tag_}
, attributes{attributes_}
, single_tag{single_tag_}
{}
XML_ElementT::XML_ElementT(void){}

//overloaded extraction operator
std::ostream& operator << (std::ostream &out, XML_ElementT const& element){

    for (std::size_t i = 0; i < element.attributes.size()-1; ++i){
        out << element.attributes[i]; //<- Does not work
    }
    return out;// << element.attributes[element.attributes.size()-1];
}


错误:

undefined reference to `operator<<(std::basic_ostream<char, std::char_traits<char> >&, XML_AttributeT const&)


我该如何工作?

最佳答案

未定义对`operator <&,XML_AttributeT const&)的引用


该错误意味着编译器已经正确解析了代码,并且您为操作员声明了上面的签名。但是,链接器在您的程序中找不到该函数的定义。这可能是由不同的原因引起的,例如未能链接库或定义了运算符的.o。

关于c++ - 对另一个类中的一个类使用重载运算符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12487630/

10-11 22:57
查看更多