2014-10-10 108 views
0

我正在爲作業分配使用單獨的編譯,並且有關於訪問我創建的類的數據成員的問題。當實現一個沒有接受任何參數的類的成員函數時,我需要訪問該類的數據成員,我將如何在C++中執行此操作?我知道在Java中,有this關鍵字指向調用該函數的對象。這是訪問類的數據成員的正確方法嗎?

我的頭文件:

#ifndef _POLYNOMIAL_H 
#define _POLYNOMIAL_H 
#include <iostream> 
#include <vector> 

class Polynomial { 

    private: 
     std::vector<int> polynomial; 

    public: 
     // Default constructor 
     Polynomial(); 

     // Parameterized constructor 
     Polynomial(std::vector<int> poly); 

     // Return the degree of of a polynomial. 
     int degree(); 
}; 
#endif 

我實現文件:

#include "Polynomial.h" 

Polynomial::Polynomial() { 
     // Some code 
} 

Polynomial::Polynomial(std::vector<int> poly) { 
    // Some code 
} 

int degree() { 
    // How would I access the data members of the object that calls this method? 
    // Example: polynomialOne.degree(), How would I access the data members of 
    // polynomialOne? 
} 

我能夠直接訪問私有數據成員polynomial,但我想知道如果這是正確的方式來訪問一個對象的數據成員還是必須使用類似於Java的this關鍵字的東西來訪問特定對象的數據成員?

+0

不止你經常使用數據成員的名稱而不是'this-> xxx'。如果您的參數名稱恰好與數據成員名稱相同,則參數優先,但您可以使用'this-> xxx'直接引用數據成員。 – 0x499602D2 2014-10-10 20:10:51

回答

5

該函數應該使用Polynomial::前綴定義爲Polynomial的成員。

int Polynomial::degree() { 
} 

然後,您可以訪問成員變量,如向量polynomial

+0

所以在C++中,在實現成員函數時直接使用成員變量是很好的做法? – AvP 2014-10-10 20:20:32

+0

是的。事實上,如果成員變量聲明爲'private',則成員函數是可以訪問這些變量的* only *函數。 – CoryKramer 2014-10-10 20:21:42

0

您需要將您的函數定義的範圍限定爲您的類,以便編譯器知道該度數屬於多項式。然後你可以訪問你的成員變量,如下所示:

int Polynomial::degree() { 
    int value = polynomial[0]; 
} 

沒有確定學位給你的班級兩件事情正在發生。您的Polynomial類具有未定義的degree()函數。並且您的.cpp文件中定義了degree()函數,該函數是不屬於任何類的獨立函數,因此您無法訪問Polynomial的成員變量。

0

你忘了給「度數()」函數添加一個「Polynomial ::」。

您認爲您編寫的「degree()」函數是「Polynomial」類的一部分,但編譯器將其視爲獨立的「全局」函數。

所以:

int degree() { 
    // How would I access the data members of the object that calls this method? 
    // Example: polynomialOne.degree(), How would I access the data members of 
    // polynomialOne? 
} 

應該是:

int Polynomial::degree() { 
    int SomeValue = 0; 

    // Do something with "this->polynomial;" and "SomeValue" 

    return SomeValue; 
} 

乾杯。

相關問題