xiannv2b 发表于 2022-4-24 09:39:16

C++静态方法

getcount方法输出的永远是1,即使把return count改成return 0也一样
经测试,把getcount方法改成count属性,会得到想要的


#include <iostream>

class Dog
{
public:
    Dog();
    ~Dog();
    int getcount();

private:
    static int count;
};

int Dog::count = 0;

Dog::Dog()
{
    count += 1;
    std::cout << "add" << '\n';
}

Dog::~Dog()
{
    count -= 1;
    std::cout << "subtract" << '\n';
}

int Dog::getcount()
{
    return count;
}

int main()
{
    std::cout << Dog::getcount << '\n';
    Dog dog1; Dog dog2;
    std::cout << "count = " << Dog::getcount << '\n';
    {
      Dog dog3;
      std::cout << "count = " << Dog::getcount << '\n';
    }
    std::cout << "count = " << Dog::getcount << '\n';
}
结果

jhanker 发表于 2022-4-24 09:39:17

改成下面这样就可以了!

#include <iostream>

class Dog
{
public:
    Dog();
    ~Dog();
static int getcount();//此处加上 static
private:
   static int count;
};

int Dog::count = 0;

Dog::Dog()
{
    count += 1;
    std::cout << "add" << '\n';
}

Dog::~Dog()
{
    count -= 1;
    std::cout << "subtract" << '\n';
}

int Dog::getcount()
{
    return count;
}

int main()
{
    std::cout <<"Dog::getcount"<< '\n';
   Dog dog1; Dog dog2;
    std::cout << "count = " << Dog::getcount() << '\n';//加上(),原先函数调用少了()
    {
      Dog dog3;
      std::cout << "count = " << Dog::getcount() << '\n';//加上(),原先函数调用少了()
    }
    std::cout << "count = " << Dog::getcount() << '\n';//加上(),原先函数调用少了()
        return 0;
}

jhanker 发表于 2022-4-24 09:55:55

std::cout << Dog::getcount << '\n';
std::cout << "count = " << Dog::getcount << '\n';
std::cout << "count = " << Dog::getcount << '\n';
std::cout << "count = " << Dog::getcount << '\n';
这几句代码都是有问题的。对于类本身无法调用getcount ()函数
页: [1]
查看完整版本: C++静态方法