【问题标题】:Why "<<" operator can be inherited but ">>" operator can't?为什么“<<”操作符可以被继承而“>>”操作符不能?
【发布时间】:2014-12-23 11:38:10
【问题描述】:

如果这只是一个愚蠢的问题,请原谅我。我还是 C++ 新手,这是我的实践。我正在尝试使用从 Unit Object 继承的 Actor Object 和 Enemy Object 创建一个简单的游戏。我将 Actor 和 Enemy 共享的所有统计信息和重载运算符放在 Unit 类中。这是每个类文件的简化代码:

注意:如果这段代码太长,请阅读 Actor.cpp 上的错误并跳过所有这些。我写所有这些是因为我不知道我的错误从哪里开始。

单位.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

单位.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;
}

演员.h

#ifndef ACTOR_H_INCLUDED
#define ACTOR_H_INCLUDED

#include "Unit.h"

class Actor: public Unit{
    public:
        void saveActor();
        void loadActor();
};

#endif

演员.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();
}

此代码已简化,我的真实代码包括 HP、MP、atk、def、mag、agi,每个字段的集合和获取与名称字段完全相同。这就是为什么我需要重载“>”运算符。

我的 IDE(Visual Studio)说:

错误 C2678:二进制“>>”:未找到采用“std::istream”类型左侧操作数的运算符(或没有可接受的转换)

我的问题是:

  1. 为什么Actor类可以继承重载的插入操作符,但不能继承重载的提取操作符?
  2. 将这些标准库包含在我的头文件中是个好主意还是应该包含在 cpp 文件中?

第一个问题是我的问题。第二个只是我的好奇心,各位有经验的程序员可以给我一个建议。

对不起,我的语言不好。英语不是我的主要语言。

【问题讨论】:

    标签: c++ inheritance operator-overloading


    【解决方案1】:

    您正在直播Actor*

    ofs << this;
    ifs >> this;
    

    而不是流式传输Actor

    ofs << *this;
    ifs >> *this;
    

    ofs 行有效是因为它调用 operator&lt;&lt; 的重载来打印指针,而不是因为它调用 Unit 的重载。

    【讨论】:

      猜你喜欢
      • 2016-05-29
      • 2018-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多