Оператор C ++ >> перегрузка

0

У меня есть класс клиентов следующим образом:

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include "SimpleDate.h"

using namespace std;

class Customer {

private:
    string customerId;
    string name;
    string address;
    string city;
    string postCode;
    SimpleDate* dateLastPurchased;
    double dollarsOwed;

public:
    //Customer(string customerIdVal, string nameVal);
    Customer();
    string getCustomerId();
    string getName();
    void setAddress(string addressVal);
    string getAddress();
    void setPostCode(string postCodeVal);
    string getPostCode();
    void setCity(string cityVal);
    string getCity();
    void setDateLastPurchased(SimpleDate* date);
    SimpleDate* getDateLastPurchased();
    void addDollarsOwed(double amount);
    double getDollarsOwed();

    friend ostream& operator<< (ostream &out, Customer &cust);
    friend istream& operator>> (istream &in, Customer &cust);
};

Перегрузка разделов в файле cpp выглядит следующим образом:

ostream& operator<< (ostream &out, Customer &cust)
{
    out << cust.customerId << "\t" << cust.name << "\t" << cust.address << "\t" << cust.city << "\t" << cust.postCode << "\t" << cust.dateLastPurchased->getFullDate() << "\t" << cust.dollarsOwed << "\t" << std::endl;
    return out;
}

istream& operator>> (istream &in, Customer &cust)
{
    in >> cust.customerId;
    in >> cust.name;
    in >> cust.address;
    in >> cust.city;
    in >> cust.postCode;

    string stringData;
    in >> stringData;

    std::istringstream iss(stringData);
    std::string datePart;
    int tmp;
    vector<int> dateData;

    while(std::getline(iss, datePart, '/')) {

        sscanf(datePart.c_str(), "%d", &tmp);       
        dateData.push_back(tmp);
    }

    SimpleDate* date = new SimpleDate(dateData[2], dateData[1], dateData[0]);
    cust.dateLastPurchased = date;

    string stringDollarsOwed;
    in >> stringDollarsOwed;

    sscanf(stringDollarsOwed.c_str(), "%lf", &cust.dollarsOwed);

    return in;
}

Затем в моем основном классе я пытаюсь создать объект клиента следующим образом:

Customer* cust = new Customer();

    cust << customerInfo[0] << customerInfo[1] << customerInfo[2] << customerInfo[3] << customerInfo[4] << customerInfo[5] << customerInfo[6];

Но когда я компилирую, я получаю следующую ошибку,

вы можете помочь?

Благодарю.

AppManager.cpp: In member function 'Customer* AppManager::createCustomerObject(std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >)':
AppManager.cpp:445: error: no match for 'operator<<' in '& cust << customerInfo.std::vector<_Tp, _Alloc>::operator[] [with _Tp = std::basic_string<char, std::char_traits<char>, std::allocator<char> >, _Alloc = std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >](0u)'
Customer.h:46: note: candidates are: std::ostream& operator<<(std::ostream&, Customer&)
*** Error code 1
make: Fatal error: Command failed for target 'Tour'
Теги:
operator-overloading

2 ответа

0
Лучший ответ

Кажется, вы вставляете объекты customerInfo [0] и т.д. В объект cust, который вы создали. Вы не можете вставить один объект в другой. Оператор вставки/извлечения при перегрузке может использоваться только с такими примитивными типами данных, как хранение и отображение значений в объектах.

  • 0
    Я пытаюсь установить свойства клиента, customerInfo [0] является строковым значением
  • 0
    Если вы хотите прочитать значения из строки в объект, то вам нужно написать отдельную функцию, которая может проанализировать строку (может быть, ваша строка '', ',' - ',' _ 'и т. Д. Разделена) и заполнить поля объекта.
Показать ещё 1 комментарий
1

Этот оператор:

ostream& operator<< (ostream &out, Customer &cust)

позволяет вам делать что-то вроде

Customer c;
std::cout << c << std::endl;
std::ofstream output("customers.txt");
output << c << std::endl;

и не

Customer c;
c << x;

и определенно не

Customer* c = ...;
c << x;
  • 0
    Я пытаюсь установить свойства клиента, customerInfo [0] является строковым значением

Ещё вопросы

Сообщество Overcoder
Наверх
Меню