没有包含好友的如何使用重载运算符?

时间:2018-02-19 09:08:20

标签: c++

用于单元测试:

 ostream& operator << (ostream&os,const Unit&C)
 {

     os << C.GetUnitName() << C.GetUnitID() << C.GetCredits();
     return os;
 }

 istream& operator >> (istream&input,Unit&C)
 {
     string UnitName,UnitsID;
     int Crediet;
     input >> UnitName >> UnitsID>> Crediet;

    C.setUnitName(UnitName);
    C.setUnitID(UnitsID);
    C.setCredits(Crediet);

    return input;
}

文本输入文件:数据库ICT222 3

为什么我得到outfile:“0x6afd64”?

1 个答案:

答案 0 :(得分:1)

  

如何在没有包含好友的情况下使用重载运算符?

你可以总是过载而没有朋友,只要你 onl 在运营商中使用你的班级的公共成员......

如果您需要内部,运气不好,那么您需要朋友声明。但是,您可以有条件地编译它,仅用于您的测试版本:

class C
{
#ifdef SOME_MACRO_IDENTIFYING_UT_BUILD
    friend auto operator<<(/* ... */) { /* ... */ }
#endif
};

但是,您也无法阻止用户定义宏。变体:

class C
{
#ifdef SOME_MACRO_IDENTIFYING_UT_BUILD
    friend
#endif
     auto operator<<(/*...*/); // no implementation in header
};

(或者只是完全跳过ifdef / endif,并不重要......)

然后在CPP文件中(已编译,因此除非有源,否则用户不能影响;但不适用于模板):

#ifdef SOME_MACRO_IDENTIFYING_UT_BUILD
auto operator<<(/* ... */)
{
    // implementation showing your internals
}
#else
auto operator<<(/* ... */)
{
    // some implementation you consider safe for general use...
    //
    // if you don't want the user to use it at all, you
    // even might throw an exception - I don't consider
    // it the best idea, but at least...
}
#endif

您需要做的就是使用宏定义的GCC / clang运行特定的测试构建:-D选项,MSVC / D.