我已经完成了以下运算符重载,它在以下类对象上按预期工作。 但是当我将这个指针传递给 vector 中的类对象时,输出流不起作用 (按照我定义的方式)
对于这类问题,我很抱歉,但我是 C++ 的新手,我不知道如何准确地提出这个问题。
运算符重载:(shape.cpp)
ostream &operator<<(ostream &output, Shape &S)
{
output << S.name << " (" << S.id << ") " << endl;
return output;
}
内部形状类(shape.h): friend ostream& operator<<(ostream& output, Shape &S);
main.cpp:
#include <iostream>
#include <vector>
using std::cout;
int main()
{
vector<Shape*> array;
Shape * s1 = new Shape("Square");
array.push_back(s1);
cout << *s1; //Prints "Square (1)"
cout << array[0]; //Prints "007CADC8" maybe hex address of vector element?
return 0;
}
最佳答案
这失败了,因为你正在输出 Shape *
,类似于如果你做了 cout << s1
会发生什么.您需要执行与前一行相同的操作并取消引用 vector 中包含的指针:
cout << *array[0];
关于c++ - 访问包含它的 vector 元素时,类对象的运算符重载不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27608431/