【发布时间】:2014-10-10 20:05:34
【问题描述】:
我正在为家庭作业使用单独编译,并且我有一个关于访问我创建的类的数据成员的问题。当实现一个不带任何参数的类的成员函数并且我需要访问该类的数据成员时,我将如何在 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直接引用该数据成员。
标签: c++ class implementation