这是访问类的数据成员的正确方法吗?

时间:2014-10-10 20:05:35

标签: c++ class implementation

我正在使用单独的编译进行家庭作业,我有一个关于访问我创建的类的数据成员的问题。当实现不带任何参数的类的成员函数并且我需要访问该类的数据成员时,我将如何在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关键字用于访问特定对象数据成员吗?

3 个答案:

答案 0 :(得分:5)

应使用Polynomial前缀将此函数定义为Polynomial::的成员。

int Polynomial::degree() {
}

然后您可以访问成员变量,例如向量polynomial

答案 1 :(得分:0)

您需要将度函数的函数定义范围限定为您的类,以便编译器知道该度数属于多项式。然后你可以像这样访问你的成员变量:

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

如果你的课程没有确定学位,就会发生两件事情。您的Polynomial类具有定义的degree()函数,没有任何定义。并且你的.cpp文件中定义了degree()函数,它是一个不属于任何类的独立函数,因此你无法访问多项式的成员变量。

答案 2 :(得分:0)

您忘了在“degree()”函数中添加“Polynomial ::”。

您认为您编写的“degree()”函数是“多项式”类的一部分,但编译器会将其视为独立的“全局”函数。

所以:

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;
}

干杯。