静态功能错误 [英] static function error

查看:73
本文介绍了静态功能错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好。我有以下代码。它出什么问题了?我有一些错误...



Hi. I have the following code. What's wrong with it? I have some error...

class test
{
private:
	 int a, b;
public:
    static void set_ab(int newA, int newB)
	{
		a = newA;
		b = newB;
	}
};

int main(void)
{
	test::set_ab(1, 2);
	return 0;
}

推荐答案

您的会员 a b 实例成员,而不是静态成员。您正尝试从静态函数访问它们。但他们可以成为什么样的实例的成员?静态函数无法访问它们,因为它没有给出任何实例的信息。比如说,你可以有实例发送myFirstText文本,mySecondTest; 然后你会有不同的对象 myFirstTest.a mySecondTest.a 。但是静态函数没有引用任何实例;甚至不会知道 myFirstText mySecondTest 存在。



一些背景:与静态函数相比,实例函数有额外的隐式参数this,用于引用实例。



-SA
You members a and b are instance members, not static ones. You are trying to access them from a static function. But members of what instance could they be? Static function cannot access them, because it isn't given any information in which instance is that. Say, you could have instances text myFirstText, mySecondTest; then you would have different objects: myFirstTest.a and mySecondTest.a. But a static function doesn't has no reference to any instance; would not even "know" that myFirstText or mySecondTest exist.

Some background: in contrast to static functions, instance functions have additional implicit parameter "this", which is used to reference the instance.

—SA


这篇关于静态功能错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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