如何用过载输出来控制"这个"?
How to cout 'this' with overloaded output?
在下面的示例中,如何引用当前对象实例来趁机使用输出重载?
class Shape {
private:
double _length, _width;
double straight(double value) {
if (value<0) { return -value; }
if (value==0) { return 1; }
return value;
}
public:
Shape() { setDims(1,1); }
Shape(double length, double width) {
setDims(length, width); }
void setDims(double length, double width) {
_length=straight(length); _width=straight(width); }
friend ostream &operator<<(ostream &output, Shape &S) {
output << S._length << "," << S._width; return output; }
void display() { cout << [THIS] << endl; }
};
int main(int argc, const char * argv[]) {
Shape s1; s1.display();
return 0;
}
就像这样:
void display() { cout << *this << endl; }
this
是一个指针。您的operator<<
需要一个实际的Shape
对象,而不是指针。
因此,您必须先取消引用指针:*this
。
或者只使用运算符<<
#include <iostream>
using namespace std;
class Shape {
private:
double _length, _width;
double straight(double value) {
if (value<0) { return -value; }
if (value == 0) { return 1; }
return value;
}
public:
Shape() { setDims(1, 1); }
Shape(double length, double width) {
setDims(length, width);
}
void setDims(double length, double width) {
_length = straight(length); _width = straight(width);
}
friend ostream &operator<<(ostream &output, Shape &S) {
output << S._length << "," << S._width; return output;
}
int main(int argc, const char * argv[]) {
Shape s1;
std::cout << s1 << std::endl;
}
相关文章:
- 有人能分解一下这个c++模板的语法吗
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 为什么这个函数将"const char*"转换为"void* const"而不是"const void*"
- 为什么在这个代码结束循环中没有得到结束
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 控制允许动态运行c++的并发操作数
- 如何在BST的这个简单递归实现中消除警告
- 从控制台中删除最后打印的元素
- 如何将这个C++哈希表转换为动态扩展和收缩,而不是使用硬设置的最大值
- 这个指针在c++中的用法
- 这个语法std::class<>{}(arg1, arg2) 在C++中是什么意思?
- 书中的这个例子不好吗
- 计算每个节点的树高,帮助我解释这个代码解决方案
- 为什么这个 c++ 代码打印出长度 5,当我打印出字符串时,程序会自动终止?
- 是否可以使用if constexpr删除控制流语句
- 为什么这个音频包络不能通过开关的情况?
- 控制达到非空功能结束.我该如何解决这个问题
- 如何用过载输出来控制"这个"?
- 这个流控制关键字类标识符的结构是什么?
- 在这段代码中,我有一个警告:控制达到非void函数的结束[- return-type].我怎样才能解决这个问题