我正在为作业分配使用单独的编译,并且有关于访问我创建的类的数据成员的问题。当实现一个没有接受任何参数的类的成员函数时,我需要访问该类的数据成员,我将如何在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