如何在静态函数中使用成员变量 [英] How to use a member variable in static function

查看:77
本文介绍了如何在静态函数中使用成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    #include   <   iostream  >  
< span class =code-keyword>使用 命名空间 :: std;
class 学生
{
int rollno,age;
public
static void getData()
{
cin>> rollno;
cin>>年龄;
}
静态 void showData()
{
cout<< rollno:<< rollno<< age:<< age;
}
};
int main()
{
学生s1;
s1.getData();
s1.showData();
Student :: getData();
Student :: showData();
}





我的尝试:



i试图将变量更改为静态然后它也不起作用

解决方案

静态函数没有访问权限就不那么明显了非静态成员(称为实例成员)?

如果将字段更改为静态则这很糟糕。更好地改变实例函数的功能。



静态函数很好;而且,如果他们不使用实例,它们应该是静态的,它们起着一种实用功能的作用;并且它还节省了一些处理器周期以获得更好的性能(如果你不这样做,性能泄漏分析器会给你一个警告)。



但静态字段很糟糕,最好避免。如果你需要单例行为,例如,使用实现良好的单例模式,这也应该是最好的避免,但更容易接受。



-SA

#include<iostream>
using namespace::std;
class Student 
{
	int rollno,age;
	public :
	static void getData()
	{
		cin>>rollno;
		cin>>age;
	}
	static void showData()
	{
		cout<<"rollno : "<<rollno<<"age : "<<age;
	}
};
int main()
{
	Student s1;
	s1.getData();
	s1.showData();
	Student::getData();
	Student::showData();
}



What I have tried:

i have tried to change the variable to static then also it does not work

解决方案

Isn't that obvious that static functions don't have access to non-static members (called instance members)?
If you change the field to static this is bad. Better change function to an instance function.

Static function are just fine; moreover, if they don't use an instance, they should be static, they play role of a kind of utility functions; and also it saves a bit of processor cycles for a bit better performance (performance leak analyzers will give you a warning if you don't do so).

But static fields are bad, are best avoided. If you need singleton behavior, for example, use well implemented singleton pattern, which also should be best avoided, but is more acceptable.

—SA


这篇关于如何在静态函数中使用成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆