我正在爲作業分配使用單獨的編譯,並且有關於訪問我創建的類的數據成員的問題。當實現一個沒有接受任何參數的類的成員函數時,我需要訪問該類的數據成員,我將如何在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
關鍵字的東西來訪問特定對象的數據成員?
不止你經常使用數據成員的名稱而不是'this-> xxx'。如果您的參數名稱恰好與數據成員名稱相同,則參數優先,但您可以使用'this-> xxx'直接引用數據成員。 – 0x499602D2 2014-10-10 20:10:51