尝试将player类传入wanderingSoul构造函数时遇类型转换错误
Hey, let's break down this error and fix it step by step. The core issue here is that you're trying to create a wanderingSoul object using a player object directly—but these are two unrelated classes, so the compiler has no idea how to convert a player into a wanderingSoul. It's falling back to trying the move constructor for wanderingSoul, which expects a wanderingSoul (not a player), hence the mismatch error.
The Key Fix: Adjust the wanderingSoul Constructor
Your wanderingSoul class doesn't have a constructor designed to accept a player object. Here are the two most logical solutions based on what your game needs:
1. Have wanderingSoul hold a reference/pointer to the player
If the wandering soul needs to interact with the existing player (e.g., track their position, attack them), modify the wanderingSoul class to take a player reference or pointer in its constructor:
// In wanderingSoul.h #include "player.h" // Don't forget to include the player class header class wanderingSoul { private: player* m_targetPlayer; // Use a pointer if you might reassign the target later // Or player& m_targetPlayer; // Use a reference if the player will exist for the soul's entire lifetime public: // Constructor that accepts a player reference wanderingSoul(player& playerRef) : m_targetPlayer(&playerRef) {} // Initialize pointer with the player's address // If using a reference instead: // wanderingSoul(player& playerRef) // : m_targetPlayer(playerRef) {} };
Then in your game.cpp code, the call will work correctly:
// Battle Test wanderingSoul wanderS(main); // Now passing the player object to the correct constructor
2. Add a Conversion Constructor (Use Only If Logical)
If your game logic allows a wanderingSoul to be created directly from a player (e.g., the player transforms into a wandering soul), you can add a conversion constructor to wanderingSoul:
// In wanderingSoul.h class wanderingSoul { private: // Copy relevant player data here (e.g., health, position) int m_health; float m_xPos; float m_yPos; public: // Conversion constructor from player to wanderingSoul wanderingSoul(const player& p) { // Copy the data you need from the player object m_health = p.getHealth(); // Assume player has a getHealth() method m_xPos = p.getXPos(); // Assume player has position getters m_yPos = p.getYPos(); } };
This lets you create a wanderingSoul directly from a player, but only use this if it fits your game's design.
Why the Original Error Popped Up
The compiler searched for a wanderingSoul constructor that accepts a player—when it couldn't find one, it tried to use other available constructors (like the move constructor wanderingSoul(wanderingSoul&&)). Since your argument is a player (not a wanderingSoul), this conversion isn't allowed, resulting in the error you saw.
内容的提问来源于stack exchange,提问作者Fabian

