2014-11-23 155 views
-2

我想實現由兩個點代表矩形的對角組成的類Rectangle。 Point結構已經在頭文件中聲明。我不知道如何在Rectangle類的struct類中使用x,y。C++結構與類

的是.h文件:

struct Point { 
    double x, y; 
}; 

// Define your class below this line 
class Rectangle 
{ 
public: 
    Rectangle(double p.x, double p.y, double w, double h); 
    double getArea() const; 
    double getWidth() const; 
    double getHeight() const; 
    double getX() const; 
    double getY() const; 

    void setLocation(double x, double y); 
    void setHeight(double w, double h); 
private: 
    Point p; 
    double width; 
    double height; 

}; 

在我的.cpp初始化,如:

Rectangle::Rectangle(double p.x, double p.y, double w, double h) 
:(p.x),(p.y), width(w), height(h) 
{ 

} 
+0

使用兩個參數爲Point創建構造函數,並在Rectangle構造函數的初始化程序列表中調用它 – Maxwe11 2014-11-23 22:21:55

+0

您的代碼與您的描述不符。你說過要用兩個代表對角的點來定義它。你實際上使用了一個點和兩個維度(寬度和高度)。 – Persixty 2014-11-23 22:22:14

+0

「如何使用」?什麼? – 2014-11-24 01:13:12

回答

2

您可以爲點構造,像這樣:

struct Point { 
    double x, y; 
    Point(double xx, double yy): x(xx), y(yy){} 
}; 

然後將矩形中的構造函數更改爲:

Rectangle::Rectangle(double x, double y, double w, double h) 
:p(x,y), width(w), height(h) 
{ 
} 

如果您使用的是C++ 11,您還有一個附加選項。由於PointAggregate結構juanchopanza建議像這樣你就可以將其初始化:

Rectangle::Rectangle(double x, double y, double w, double h) 
:p{x,y}, width(w), height(h) 
{ 
} 

這樣做的好處是,你並不需要一個構造函數添加到Point結構,如果你選擇這種方式。

+0

@ juanchopanza,謝謝,我得到那些2有時困惑:) – shuttle87 2014-11-23 22:53:10