定义<<基类的运算符

时间:2015-02-10 09:35:55

标签: c++

我正在尝试为基类定义<< operator,以便稍后可以轻松打印每个对象的标识符。

我尝试过SSCCE,但我不知道问题出在哪里,因为我正在打印方向而不是内容。我不知道打印vector位置或打印std::string(char[])是否出现问题。

main.cpp中:

#include "City.h"
#include <vector>
#include <iostream>

int main() {
    std::vector<Location*> locations;
    locations.push_back(new City("TEST"));

    for(unsigned int it = 0; it<locations.size(); it++){
        std::cout << locations[it] << std::endl;
    }
    return 0;
}

Location.h:

#include <cstring>
#include <string>

class Location {
public:
    Location(const std::string id);
    friend std::ostream& operator<<(std::ostream& os, Location& loc);
    std::string GetId();

private:
    // Name/identifier of the location
    char ID[5];
};

Location.cpp:

#include "Location.h"

Location::Location(const std::string id){
    memset(this->ID, 0, 5);
    strncpy(this->ID, id.c_str(), 5); // I have it as a char[5] at a larger app
}

std::string Location::GetId(){
    return std::string(this->ID);
}

std::ostream& operator<<(std::ostream& os, Location& loc){
    os << loc.GetId();
    return os;
}

City.h:

#include "Location.h"

class City: public Location{
public:
    City(std::string id);
};

City.cpp:

#include "City.h"

City::City(const std::string id) : Location(id){

}

有什么想法吗?

0 个答案:

没有答案