为什么我的私有变量不适用于成员函数 [英] Why my private variables are not acessible to member functiom
本文介绍了为什么我的私有变量不适用于成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
void dooperation()
{
cout<< x + y;
}
即使x,y现在是类添加的私有成员......为什么它们超出范围会员dooperation();
我尝试过:
#include< iostream>使用namespace std
;
模板< class T>
类计算器
{
受保护:
T x;
T y;
public:
calculator(T m,T n)
{
x = m;
y = n;
}
virtual void dooperation()= 0;
};
模板< class T>
class addition:public calculator< T>
{
public:
addition(T m,T n):calculator< T>(m,n)
{
}
void dooperation()
{
cout<< x + y;
}
};
int main()
{
addition< int>添加(3,4);
计算器< int> * ptr;
ptr =& add;
ptr-> dooperation();
}
解决方案
这里与私人会员无关(你的代码中没有私人会员)但是事实上这些名字是不依赖的。
详情请见标准C ++ FAQ:当我的模板派生类使用从模板基类继承的成员时,为什么会出现错误? [ ^ ]并提供解决方案:
void dooperation()
{
cout<< 此 - > x + 此 - > y;
}
当您需要外部访问私有成员时,最好实现公共getter。返回的值应该是常量,并且通过ref来避免问题和开销。
public :
const T& getX(){ return x; }
void dooperation() { cout<<x+y; }
even though x ,y are now private menmbers of class addition ...why are they out of scope of member dooperation();
What I have tried:
#include <iostream> using namespace std; template<class T> class calculator { protected: T x; T y; public: calculator(T m,T n) { x=m; y=n; } virtual void dooperation()=0; }; template<class T> class addition: public calculator<T> { public: addition(T m,T n):calculator<T>(m,n) { } void dooperation() { cout<<x+y; } }; int main() { addition<int> add(3,4); calculator <int>* ptr; ptr=&add; ptr->dooperation(); }
解决方案
It is not related to private members here (you do not have any in your code) but to the fact that the names are non-dependant.
It is explained in detail at Standard C++ FAQ: Why am I getting errors when my template-derived-class uses a member it inherits from its template-base-class?[^] and provides the solution:
void dooperation() { cout << this->x + this->y; }
When you need external access to private members it is best to implement public getters. The returned value should be constant and by ref for avoiding problems and overhead.
public: const T& getX() { return x; }
这篇关于为什么我的私有变量不适用于成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文