简体   繁体   中英

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

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.

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++.

the thing your doing is printing entire object, but << operator is not defined to print any object, that you have to do yourself. try this, std::cout<<user.damageSpells[0].damage<<user.damageSpells[0].manaCost

and so on...... and for subclass too

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM