2014-10-10 82 views
0

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

+0

不止你经常使用数据成员的名称而不是'this-> xxx'。如果您的参数名称恰好与数据成员名称相同,则参数优先,但您可以使用'this-> xxx'直接引用数据成员。 – 0x499602D2 2014-10-10 20:10:51

回答

5

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

int Polynomial::degree() { 
} 

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

+0

所以在C++中,在实现成员函数时直接使用成员变量是很好的做法? – AvP 2014-10-10 20:20:32

+0

是的。事实上,如果成员变量声明为'private',则成员函数是可以访问这些变量的* only *函数。 – CoryKramer 2014-10-10 20:21:42

0

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

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

没有确定学位给你的班级两件事情正在发生。您的Polynomial类具有未定义的degree()函数。并且您的.cpp文件中定义了degree()函数,该函数是不属于任何类的独立函数,因此您无法访问Polynomial的成员变量。

0

你忘了给“度数()”函数添加一个“Polynomial ::”。

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

所以:

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

干杯。

相关问题