c++ - 静态函数 static bool 类型 问题
PHPz
PHPz 2017-04-17 11:03:26
0
2
1314

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

PHPz
PHPz

学习是最好的投资!

reply all(2)
巴扎黑

I suggest you post the code. I have summarized some knowledge points about static data members and static member functions. I hope it will be useful to you!

Static member functions are not associated with any object, so

1. Non-static data members belonging to class objects cannot be accessed

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

2. Unable to access non-static member functions

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. Only other static member functions can be called

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: Static data members must be defined outside the class

刘奇

There is a problem with what was said above. It is best for static functions to only reference static data members, but they can also reference non-static data members. If you refer to non-static data members in the object, you can declare the function static bool foo(A & a). lzThe const std::string& iVariable here is not a data member in class A. Why should we use a static function to handle it?

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template