我正在为作业分配使用单独的编译,并且我有一个关于访问我创建的类的数据成员的问题。当实现一个不带任何参数的类的成员函数并且我需要访问该类的数据成员时,我将如何在 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?
}
我能够直接访问私有(private)数据成员多项式
,但我想知道这是否是访问对象数据成员的正确方法,或者我是否必须使用类似于 Java 的 this
关键字访问特定对象的数据成员?
最佳答案
此函数应使用 Polynomial::
前缀定义为 Polynomial
的成员。
int Polynomial::degree() {
}
然后就可以访问 vector 多项式
等成员变量了。
关于c++ - 这是访问类数据成员的正确方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26307247/