Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No match for ‘operator<<’ when trying to print vector element

Tags:

c++

vector

I am making a text based adventure game called Magick.
In this game I have a class labeled damageSpell it looks like this

class damageSpell { 
    public:
        int damage;
        SubClasses type;
        int manaCost;
        std::string spellDescription; 
};

I used this class as the type for a vector like so

std::vector<damageSpell> damageSpells

Later on, I attempted to add an element into my damageSpells vector, by using the insert function on vector.

damageSpell fireball;

user.damageSpells.insert(user.damageSpells.begin(), 0, fireball);

Then attempted to print it out

std::cout << user.damageSpells[0];

Upon doing this I received this error

magick1.cpp:252:15: error: no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream}’ and ‘damageSpell’)

I am new to C++ and have no idea what this means or how I should go about fixing it, any and all help will be appreciated.

like image 340
Alice The Hatter Avatar asked Oct 23 '25 16:10

Alice The Hatter


1 Answers

user.damageSpells[0] is an instance of your class spellDamage. And your compiler doesn't have any idea of how to print it. You have to define a function that will be called on << operator and will print it out.

This operator overloading can be defined like this:

std::ostream& operator<<(std::ostream& stream, const damageSpell& damageSpellToPrint)
{
    // Your code here
}

It will be called eachtime you use << operator between a std::ostream (like std::cout) and an instance of your class. For instance, the following code will directly call your operator function, passing std::cout as stream parameter and user.damageSpells[0] as damageSpellToPrint parameter:

std::cout << user.damageSpells[0];

I suggest you this post or this documentation that will help you to understand operator overloading concepts in C++.

like image 117
Aracthor Avatar answered Oct 25 '25 06:10

Aracthor