簡體   English   中英

從字符串流讀寫自定義對象時,測試失敗

[英]Tests failing, when reading and writing a custom object from and to a stringstream

沒有語法錯誤,這不是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

對於assert(actual == correct); 為了工作,兩個string應該完全相同,這在您的情況下是不正確的。

因此,請替換:

correct = 5,3,2;

Pixel_test.cpp具有:

correct = "5,3,2";

並替換為:

out << r << g << b;

std::ostream& operator<<(std::ostream& out, Pixel& pix)具有:

out << r << ',' << g << ',' << b;

out << pix;渲染相同的輸出out << pix;

通過進行上述更改,您的assert(actual == correct); 將停止失敗。

但是,之后的asserts s可能會失敗,因為當您調用in>>pix; 該函數被調用為:

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;
}

而且我們可以清楚地看到,在調用它們各自的set方法之前, r gb沒有分配任何值。

因此,只有垃圾值存儲在pix rval bvalgval中。

這就是assert的原因:

assert(pix.getRed() == 6);
assert(pix.getBlue() == 6);
assert(pix.getGreen() == 4);

必然會失敗。

編輯:

為了解決這個問題,您需要將剛剛放入流中的輸入讀入變量r gb

因此,如下更改std::istream& operator>>(std::istream& out, Pixel& pix)函數:

std::istream& operator>>(std::istream& out, Pixel& pix)
{
 int r, g, b;
 out >> r >> g >> b;
 pix.setRed(r);
 pix.setGreen(g);
 pix.setBlue(b);
 return out;
}

同時替換:

in << (6,4,6);

在您的Pixel_test.cpp文件中,其中包含:

in << "6 4 6";

因為stringstream將數據存儲為string

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM