2015-12-31 48 views
1

我一直在試圖理解默認構造函數,我想我得到它,如果它是類中唯一的構造函數。但是如果我在類中定義了多個構造函數呢?我想要做的是創建一個類「向量」,它將存儲二維向量。我需要一個構造函數來將座標設置爲主函數中給出的值。我還需要一個默認的構造函數,調用時,將座標設置爲0。我似乎無法弄清楚如何使雙方工作,在相同的代碼默認構造函數與正常構造函數的類C++

#include <iostream> 
#include <string> 
#include <cmath> 
#include <vector> 
#include <algorithm> 

using namespace std; 

class Vector { 
    double x_coord, y_coord; 
public: 
Vector(double x_coord=0, double y_coord=0); //default contructor??? 

Vector (double x, double y) //normal constructor 
{ 
    set_values (x,y); 
} 
void set_values(double new_x, double new_y) //function to set values for the vectors 
    { 
     x_coord=new_x; 
     y_coord=new_y; 
    } 
    double get_x() 
    { 
     return x_coord; 
    } 
    double get_y() 
    { 
     return y_coord; 
    } 

}; 
+0

要麼有一個構造函數'Vector(double x_coord = 0,double y_coord = 0);'它既可以作爲默認構造函數使用,因爲它可以不帶參數調用,也可以作爲雙參數構造函數使用;或者兩個構造函數,一個不帶參數,如'Vector()',另一個帶兩個'Vector(double x,double y)'。擁有一個總是帶有兩個參數的構造函數,以及可選地使用相同參數的構造函數是沒有意義的。 –

回答

1

默認構造函數構造函數調用時在定義class的實例時,您省略了這些缺陷。示例:

Vector vec; 

在此,執行默認構造函數(Vector::Vector(double = 0, double = 0))。

您可以刪除其他構造(Vector::Vector(double, double)),並使用這個定義的默認構造函數:

Vector(double x_coord = 0, double y_coord = 0) { 
    set_values(x_coord, y_coord); 
} 

當你傳遞兩個參數,這將被自動調用。此外,模糊性已解決:如果通過這兩個構造函數,你通過了兩個double?應該叫他們哪一個?編譯器會提出一個錯誤,說構造函數是不明確的。


注:

  • set_values功能似乎沒有用處,因爲它沒有做任何有用的工作。在構造函數中使用成員初始值設定項列表來提高性能。此外,它被認爲是良好的作風:

    Vector(double x_coord = 0, double y_coord = 0): x_coord(x_coord), y_coord(y_coord) { } 
    
  • 你大量使用getter和setter方法看起來...壞。它打破封裝。提供函數,這些函數不公開實現細節,但執行有用的操作,如move

2

我能想象使用下面的構造類的對象:

Vector v1;   // Construct with x = 0, y = 0 
Vector v2(10);  // Construct with x = 10, y = 0 
Vector v3(10, 20); // Construct with x = 10, y = 20 

可以完成這一切只用一個構造函數:

Vector(double x=0, double y=0) : x_coord(x), y_coord(y) {} 

你不需要第二個構造函數。

+0

非常感謝,這似乎是一個非常乾淨的做法 –

1

沒關係,我想到了一切。 如果有人需要的答案: 你可以有你定義默認構造函數的默認和類

class Vector { 
double x_coord, y_coord; 
public: 
Vector(): x_coord(0), y_coord(0) {}; //default constructor 

Vector (double x, double y) //normal constructor 
{ 
    set_values (x,y); 
} 

它只是方式定義其他構造。

+0

只用一個構造函數就可行。看看答案! – Downvoter