我想打一个类似的行为有std::cout
:如何在C++中正确地重载“<<”运算符?
int a = 10, b = 15, c = 7;
MyBaseClass << "a = " << a << ", b = " << b << std::endl;
我尝试实施一些事情我刚读,但它不为我工作。我想在一个类中实现operator
,我称之为MyBaseClass
。我尝试这样做:
class MyBaseClass {
private:
std::ostream someOut;
public:
// My first try:
std::ostream &operator<< (std::ostream &out, const std::string &message) {
}
// The second try:
std::ostream &operator<< (const std::string &message) {
someOut << message << std::endl;
return someOut;
}
void writeMyOut() {
std::cout << someOut.str()
};
};
当我编译此,我得到:“叫‘MyBaseClass’的含蓄到删除的默认构造函数” - 什么我需要做修复它?
OS X,Xcode,clang编译器,都是最新的。
可能重复[C++初学者 - “朋友”的功能和<<运算符重载:什么是正确的方式来重载一个运算符的类?](http://stackoverflow.com/questions/2828280/c-beginner-friend-functions-and-operator-overloading-what-is-the-prope) – Joel
我觉得你的第二个尝试应该工作,或多或少。编译错误可能是因为'MyBaseClass'没有构造函数,但你需要初始化'someOut'成员。 (我并不是100%确定这是问题所在,但是如果你为'MyBaseClass'提供了一个构造函数,我想你会进一步得到一些东西。具体来说,我认为你会花费足够的时间来尝试写入未初始化的'std :: ostream'叫做'someOut'。) –
@DaveM。 - 如果我添加一个空的构造函数,我得到:'类型'std :: ostream'的字段(又名'basic_ostream')保护了默认的构造函数' –
JavaRunner