我正在编写一种方法来打印 std::cout
中的一些空格,我知道还有其他方法可以使用标准库来实现相同的目标。不管怎样,我用了typedef
存储空间的数量和 <<
的重载运算符(operator)。但是我的重载根本没有被调用,因为我的 typedef
被解释为无符号整数。
那么我该如何告诉编译器调用我的函数呢?
class MyClass {
private:
typedef unsigned int space_type;
public:
std::ostream& operator<< (std::ostream& _os, space_type _n_spaces) {
for (int _C = 0; _C < _n_spaces; _C++)
_os << " ";
return _os;
}
void PrintNumbers(char _a, char _b) {
space_type spaces = 5;
std::cout << _a << spaces << _b << std::endl;
}
}
int main () {
MyClass class_instance;
class_instance.PrintNumbers('K', 'X');
std::cin.get();
return 0;
}
这是预期的输出:
K X
这是我获得的输出:
K5X // 5 is interpreted as an unsigned int, so my overloaded function
// isn't called, instead is called the std overloading with unsigned int
最佳答案
Typedef 不创建新类型,它只是创建现有类型的别名。可能你可以使用这样的东西:
struct SpaceType {
int space_cnt;
};
...
std::ostream& operator<< (std::ostream& _os, SpaceType _n_spaces) {
for (int _C = 0; _C < _n_spaces.space_cnt; _C++)
_os << " ";
return _os;
}
...
SpaceType spaces = { 5 };
std::cout << _a << spaces << _b << std::endl;
关于C++ << 相同类型的运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29450129/