Mas*_*gol 0 c++ inheritance operator-overloading
如果这只是一个愚蠢的问题,请原谅我.我仍然是C++的新手,这是我的惯例.我正在尝试使用继承自Unit对象的Actor Object和Enemy Object创建一个简单的游戏.我把所有的统计数据和重载的运算符放在了Actor类的Actor和Enemy中.这是我的每个类文件的简化代码:
注意:如果此代码太长,请阅读Actor.cpp上的错误并跳过所有这些.我写了所有这些因为我不知道我的错误从哪里开始.
Unit.h
#ifndef UNIT_H_INCLUDED
#define UNIT_H_INCLUDED
#include <iostream>
#include <fstream>
#include <string>
class Unit{
friend std::ostream& operator<<(std::ostream&, const Unit&);
friend std::istream& operator>>(std::istream&, Unit&);
public:
Unit(std::string name = "");
void setName(std::string);
std::string getName();
std::string getInfo();
int attack(Unit&);
protected:
std::string name;
};
#endif
Run Code Online (Sandbox Code Playgroud)
Unit.cpp
#include "Unit.h"
using namespace std;
Unit::Unit(string name){
this->name = name;
}
void Unit::setName(string name){
this->name = name;
}
string Unit::getName(){
return name;
}
string Unit::getInfo(){
string info;
info = "Name\t: " + name;
return info;
}
ostream& operator<<(ostream& output, const Unit& unit){
output << unit.name << "\n";
return output;
}
istream& operator>>(istream& input, Unit& unit){
input >> unit.name;
return input;
}
Run Code Online (Sandbox Code Playgroud)
Actor.h
#ifndef ACTOR_H_INCLUDED
#define ACTOR_H_INCLUDED
#include "Unit.h"
class Actor: public Unit{
public:
void saveActor();
void loadActor();
};
#endif
Run Code Online (Sandbox Code Playgroud)
Actor.cpp
#include "Actor.h"
using namespace std;
void Actor::saveActor(){
ofstream ofs("actor.txt");
if(ofs.is_open()){
ofs << this; // This work well.
}
ofs.close();
}
void Actor::loadActor(){
ifstream ifs("actor.txt");
if(ifs.is_open()){
ifs >> this; // This is the error.
}
ifs.close();
}
Run Code Online (Sandbox Code Playgroud)
这个代码被简化了,我的真实代码包括HP,MP,atk,def,mag,agi with sets和gets for each field,就像名字字段一样.这就是我需要重载"<<"和">>"运算符的原因.
我的IDE(Visual Studio)说:
错误C2678:二进制'>>':找不到哪个运算符带有'std :: istream'类型的左操作数(或者没有可接受的转换)
我的问题是:
第一个问题是我的问题.第二个只是我的好奇心,我所有经验丰富的程序员都可以给我一个建议.
抱歉我的语言不好.英语不是我的主要语言.
你正在流媒体 Actor*
ofs << this;
ifs >> this;
Run Code Online (Sandbox Code Playgroud)
而不是流式传输Actor:
ofs << *this;
ifs >> *this;
Run Code Online (Sandbox Code Playgroud)
该ofs行有效,因为它调用operator<<打印指针的重载,而不是因为它调用你的重载Unit.