如何在 C++ 中正确重载“<<”运算符?
How to properly overload the "<<" operator in C++?
我想做出类似 std::cout
的行为:
int a = 10, b = 15, c = 7;
MyBaseClass << "a = " << a << ", b = " << b << std::endl;
我尝试实现一些我刚读过但对我不起作用的东西。我想在一个 class 中实现 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()
};
};
当我编译它时,我得到:"Call to implicity-deleted default constructor of 'MyBaseClass'" - 我需要做什么来修复它?
OS X, Xcode, clang 编译器,都是最新的。
您正在尝试将多种值类型输出到 MyBaseClass
对象中,因此需要支持相同的集合。我还将 someOut
更改为 std::ostringstream
,它能够累加输出。您可能同样希望它成为传递给构造函数的调用者提供的流的 std::ostream&
....
class MyBaseClass {
private:
std::ostringstream someOut;
public:
...other functions...
// The second try:
template <typename T>
MyBaseClass& operator<< ( const T& x ) {
someOut << x;
return *this;
}
void writeMyOut() const {
std::cout << someOut.str()
};
};
我想做出类似 std::cout
的行为:
int a = 10, b = 15, c = 7;
MyBaseClass << "a = " << a << ", b = " << b << std::endl;
我尝试实现一些我刚读过但对我不起作用的东西。我想在一个 class 中实现 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()
};
};
当我编译它时,我得到:"Call to implicity-deleted default constructor of 'MyBaseClass'" - 我需要做什么来修复它?
OS X, Xcode, clang 编译器,都是最新的。
您正在尝试将多种值类型输出到 MyBaseClass
对象中,因此需要支持相同的集合。我还将 someOut
更改为 std::ostringstream
,它能够累加输出。您可能同样希望它成为传递给构造函数的调用者提供的流的 std::ostream&
....
class MyBaseClass {
private:
std::ostringstream someOut;
public:
...other functions...
// The second try:
template <typename T>
MyBaseClass& operator<< ( const T& x ) {
someOut << x;
return *this;
}
void writeMyOut() const {
std::cout << someOut.str()
};
};