簡體   English   中英

如何將程序指向輸入到列表中的值? C ++

[英]How to point my program to the values I input into the list? C++

所以我是一個初學者,我試圖找出這個問題:

這是我的代碼:

int main()
{

  list<Shape*> shapes;
  shapes.push_back(new Pentagon(Vertex(20, 10), 8));
  shapes.push_back(new Rhombus(Vertex(50, 10), 8));

  list<Shape*>::iterator itr = shapes.begin();
  while (itr != shapes.end())
  {
    (*itr)->drawShape();    

    c.gotoXY(20, 10);
    cout << (*itr)->area();
    // scale shape (double it)
    // draw shape
    // rotate shape by 20 degrees
    // draw shape

    itr++;
  }

  cout << endl << endl << endl << endl << endl << endl << endl << endl;
  system("pause");

}

因此,基本上,第一個文本塊將兩個新對象(五角大樓和菱形)添加到列表形狀。

這些對象具有3個值,即x和y坐標以及大小。

然后在迭代器中,我試圖在工作正常的控制台中繪制這些形狀,但是c.gotoXY();出現了問題c.gotoXY(); 功能。
基本上,我希望該區域顯示在形狀的中間。 :當我在手動坐標鍵入它工作得很好(20, 10)中的代碼,為五角大樓。 您會看到它與我向列表中添加新內容時輸入的值完全相同。

但是,我將擁有許多不同的形狀,而不僅僅是手動輸入值。

我想將x和y的值鏈接到形狀列表中的對象的值,如下所示:

http://puu.sh/hlMMR/2f536907f9.png

因此,基本上,每次迭代器遍歷時,它將采用列表中下一個對象的x和y值並將其粘貼在c.gotoXY();

我希望我能解釋得足夠清楚,因為我自己幾乎看不懂它。

請幫忙。

@ edit ~~~~~~~~~~

當我嘗試使用

c.gotoXY(Vertex.getX(), Vertex.getY);

我得到這個錯誤C3867:'Vertex :: getY':函數調用缺少參數列表; 使用'&Vertex :: getY'創建一個指向成員的指針

我想象您的Shape類型具有類似以下內容的成員函數:

Vertex getPosition() const;

而且您的Vertex類型具有類似以下的成員函數:

int getX() const;
int getY() const;

在這種情況下,您可能會編寫如下代碼:

Shape* curr=*itr; //Get a pointer to the current shape from the iterator.
Vertex pos=curr->getPosition());//Get the position of the current shape.
c.gotoXY(pos.getX(),pos.getY());//Goto the current position of the current shape.

代替:

c.gotoXY(20, 10);

如果您尚未提供訪問形狀的頂點和頂點的坐標的方法-那是要解決的第一個問題。

編輯:我注意到在注釋中getX()getY()到位。 它可以訪問仍處於打開狀態的Vertex

如果Shape類還沒有此類,則合並一個getPosition()函數,該函數將返回帶有初始化對象位置的Vertex對象。 就像是:

Vertex Shape::getPosition() const
{
    return m_Position;    // position of the shape (this member would have been set by
                          // the constructor when you called, for example, 
                          // shapes.push_back(new Pentagon(Vertex(20, 10), 8)); in the 
                          // main function
}

因此,在您的main函數中,您可以調用它來獲取位置,並相應地定位形狀:

while (itr != shapes.end())
{
    (*itr)->drawShape();  

    Vertex position = (*itr)->getVertex();
    c.gotoxy(position.getX(), position.getY());

    cout << (*itr)->area();
    ++itr;
}

另外,在您對原始帖子的修改中:

c.gotoXY(Vertex.getX(), Vertex.getY);

您錯過了“()”,因此可能是:

c.gotoXY(Vertex.getX(), Vertex.getY());

但是,這是行不通的,因為您是通過類類型而不是通過對象來調用成員函數getX()getY()的。 您需要在調用類的成員函數之前聲明和初始化一個類的對象,就像我在上述while循環中對對象position所做的那樣。

暫無
暫無

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

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