首页 > 静态函数 static bool 类型 问题

静态函数 static bool 类型 问题

函数定义为static bool foo(const std::string& iVariable); 属于类A
当我在使用时 if (A::foo(Var)) 时,我发现多次调用该if语句,且使用了不同的Var时,foo返回值一直是false,是不是说静态函数的值在第一次调用时就确定了,无法改变?困惑,谢谢!!


楼上说的有问题,静态函数是最好只引用静态数据成员,但也可以引用非静态的数据成员。如果引用对象中的非静态数据成员可以声明函数static bool foo(A & a)。lz这里const std::string& iVariable并不是类A中的数据成员,为什么要用静态函数来处理呢?


建议你还是把代码贴出来。我总结了一下关于静态数据成员和静态成员函数的一些知识点,希望对你有用!

静态成员函数不和任何对象相关联,所以

1、无法访问属于类对象的非静态数据成员

class A
{
    private:
        int a;//non-static
    public:
	A(int init):a(init){}
	static getvalue(){return a;}/*错误,无法访问属于类对象的非静态数据成员*/
};

2、无法访问非静态成员函数

class A
{
    private:
        int a;//non-static
    public:
	A(int init):a(init){}
	int getvalue(){return a;}//non-static
	static printvalue(){cout << getvalue() << endl;}/*错误,无法访问非静态成员函数*/
};

3、只能调用其余的静态成员函数

class A
{
    private:
	static int staticvalue;
        int a;//non-static
    public:
	A(int init):a(init){}
	static int getvalue(){return staticvalue;}
	static printvalue(){cout << getvalue() << endl;}
};

int A::staticvalue = 2;//类外的定义

int main(int argc , char *argv[])
{
    A demo(1);
    demo.printvalue();
    A::printvalue();

    return 0;
}

BTW:静态数据成员必须在类的外部定义

【热门文章】
【热门文章】