没有语法错误,这不是Pixel_test.cpp和Pixel.cpp的完整代码。从字符串流中读取或写入自定义对象时,测试失败
我只有完整的头文件。
失败的测试是assert(actual == correct);
。
我在想,问题源于std::ostream&
和std::istream&
中的Pixel.cpp
文件。
我花了几个小时,试图明白为什么这个测试不起作用,所以我来这里得到一些帮助。
Pixel_test.cpp:
stringstream in, out;
string correct;
Pixel pix;
pix.set(5,3,2);
correct = 5,3,2;
out << pix;
string actual = out.str();
assert(actual == correct);
in << (6,4,6);
in >> pix;
assert(pix.getRed() == 6);
assert(pix.getBlue() == 6);
assert(pix.getGreen() == 4);
Pixel.cpp:
std::ostream& operator<<(std::ostream& out, const Pixel& pix)
{
int r, g, b;
r = pix.getRed();
g = pix.getGreen();
b = pix.getBlue();
out << r << g << b;
return(out);
}
std::istream& operator>>(std::istream& out, Pixel& pix)
{
int r, g, b;
pix.setRed(r);
pix.setGreen(g);
pix.setBlue(b);
out >> r >> g >> b;
return out;
}
Pixel.h:
#ifndef PIXEL_H
#define PIXEL_H
namespace imagelab
{
class Pixel
{
public:
Pixel(int r=0, int g=0, int b=0);
void set(int r, int g, int b);
void setRed(int r);
void setGreen(int g);
void setBlue(int b);
int getRed() const;
int getGreen() const;
int getBlue() const;
private:
int rval; // red 0-255
int gval; // green 0-255
int bval; // blue 0-255
};
bool operator== (const Pixel& pix1, const Pixel& pix2);
bool operator!= (const Pixel& pix1, const Pixel& pix2);
std::ostream& operator<< (std::ostream& out, const Pixel& pix);
std::istream& operator>> (std::istream& in, Pixel& pix);
}
#endif
您是否向控制台输出了“实际”和“正确”(或通过调试器查看它们的值)以查看它们是什么?除非'correct = 5,3,2;'在字符串文字周围丢失了引号,否则将ASCII值为2的字符赋值给字符串。 –
什么是变量'correct'的类型? –