沒有語法錯誤,這不是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'的類型? –