2016-09-21 52 views
0

我是新來的在C++編程。我對Java有很好的背景,但是C++在很多方面都不同,我對於.h和.cpp文件中的一個有疑問。C++類的方法調用.cpp沒有::

我有x和y位置的點對象中的以下文件:

Point.h

#ifndef POINT_H_ 
#define POINT_H_ 

class Point{ 
Point(); 
Point(int newX, int newY); 

public: 
    int getX(); 
    int getY(); 
    void setX(int newX); 
    void setY(int newY); 
    void moveBy(int moveX, int moveY); 
    Point reverse(); 
private: 
    int x; 
    int y; 
}; 
#endif 

Point.cpp

#include "Point.h" 

using namespace Point; 

Point::Point(int newX, int newY){ 
    x = newX; 
    y = newY; 
} 
int Point::getX(){ 
    return x; 
} 
int Point::getY(){ 
    return y; 
} 
void Point::setX(int newX){ 
    x = newX; 
} 
void Point::setY(int newY){ 
    y = newY; 
} 
void Point::moveBy(int moveX, int moveY){ 
    x += moveX; 
    y += moveY; 
} 
Point Point::reverse(){ 
    return Point(y,x); 
} 

我在想,如果有一個通過使用命名空間來避免Point::Point部分與std :: cout類似的方式。

謝謝

+1

沒有,因爲'Point'不是一個命名空間 –

+1

不要把函數定義在.cpp文件,只是把它們放在類定義。 – kfsone

回答

0

你無法避免的「Point::Point部分,」除非你聲明的類聲明的建築內聯。第一個「Point」定義了函數的範圍,第二個「Point」是構造函數的名稱。

但是,你可以定義構造函數(S)內聯,就像這樣:

class Point 
{ 
    Point() 
    { 
    x = 0; 
    y = 0; 
    } 
    Point(int newX, int newY); 
    { 
    x = newX; 
    y = newY; 
    } 
    // ... 
}; 

或者:

class Point 
{ 
    Point() : x(0), y(0) {} 
    Point(int newX, int newY) : x(newX), y(newY) {} 
    // ... 
}; 

或者:

class Point 
{ 
    Point(int newX = 0, int newY = 0) : x(newX), y(newY) {} 
    // ... 
}; 
1

你是不是要求來區分你的聲明和定義,而這些功能是非常的trivi人。因此將它們包含在類定義中可能實際上允許編譯器執行許多其他優化。

所以,你可以完全丟棄的.cpp和標題變爲:

#ifndef POINT_H_ 
#define POINT_H_ 

class Point 
{ 
    int x_ { 0 }; 
    int y_ { 0 }; 

public: 
    Point() = default; 
    Point(int x, int y) : x_(x), y_(y) {} 

    int getX() const { return x_; } 
    int getY() const { return y_; } 
    void setX(int x) { x_ = x; } 
    void setY(int y) { y_ = y; } 
    void moveBy(int x, int y) { x_ += x, y_ += y; } 
    Point reverse() const { return Point(y_, x_); } 
}; 

#endif 

但是,在定義類的聲明之外的成員時,你無法避免的「點::」的一部分。

1

如果你想避免的getXgetY等前面鍵入「Point::」,那麼答案是「不」,很遺憾。在C++中,任何類的名稱(如「Point」)不是命名空間,它是範圍

你只能做的是內聯該方法,定義到類聲明中。

class Point { 
    public: 
    void a_method() { 
     // all the code here! 
    } 
};