【问题标题】:Is this the proper way of accessing data members of a class?这是访问类的数据成员的正确方法吗?
【发布时间】: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-&gt;xxx。如果您有一个参数名称恰好与数据成员同名,则该参数将优先,但您可以使用this-&gt;xxx 直接引用该数据成员。

标签: c++ class implementation


【解决方案1】:

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

int Polynomial::degree() {
}

然后就可以访问向量polynomial等成员变量了。

【讨论】:

  • 那么在C++中,实现其成员函数时直接使用成员变量就可以了吗?
  • 是的。事实上,如果成员变量声明为private,则成员函数是唯一可以访问这些变量的函数。
【解决方案2】:

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

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

如果没有对您的班级进行范围界定,就会发生两件事。您的多项式类有一个未定义的 degree() 函数。并且您在 .cpp 文件中定义了 degree() 函数,该函数是一个独立函数,不属于任何类,因此您无法访问多项式的成员变量。

【讨论】:

    【解决方案3】:

    您忘记在“degree()”函数中添加“多项式::”。

    您认为您编写的“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;
    }
    

    干杯。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-22
      • 1970-01-01
      • 2016-08-06
      • 1970-01-01
      相关资源
      最近更新 更多