我一直在努力工作。無法調用指針的打印功能
我正在研究一個名爲「boxFactory」的函數,它將Box基類的指針返回給測試類。測試類然後從該指針調用打印功能。
現在我試圖在我工作其他類型之前打印方格框打印。但是,當我運行下面的代碼時,會在bptr-> print(os)處發生以下異常:
「Assignment.exe中0x0091C512處未處理的異常:0xC0000005:訪問衝突讀取位置0xCCCCCCD0」。從測試類
Box * boxFactory(char c, int w, int h){
Box * b;
if(c == 'c')
{
CheckeredBox cb;
b = &cb;
b->setHeight(h);
b->setWidth(w);
return b;
}
return NULL;
}
代碼片段:
Box * bptr = boxFactory('c',5,3);
// Check print #7
os.str(""); //reset output holder
bptr->print(os);
t.test(os.str() == "x x x\n x x \nx x x\n", "print 5x3 checkered box from factory");
從派生類格子的打印功能:
ostream& CheckeredBox::print(ostream& os) const
{
//HEIGHT for loop
for (int i = 0; i < height_; i++)
{
bool isX; //is current space x or blank
//makes the every other line starts
if (i % 2 == 0)
{
isX = true;
}
else
{
isX = false;
}
//WIDTH for loop
for (int c = 0; c < width_; c++)
{
if (isX) //utilizes isX boolean
{
os << "x";
isX = false; //oscilates bool between spaces
}
else
{
os << " ";
isX = true; //continues oscilation
}
}
os << "\n"; //append new line after each row
}
return os;
}
感謝您的快速響應。 – user3559406
但是別忘了'delete' b:C++不會自動執行此操作。或者查看'std :: unique_ptr'或'std :: shared_ptr'。 – Bathsheba