我在计算带有静态变量的对象总数的程序中出错

I have error in program to count total number of objects with static variable

本文关键字:对象 程序 出错 变量 计算 静态      更新时间:2023-10-16
using namespace std;
class Sample
{ int x;
  static int count;
   public:
  void get();
  static void showCount();
};
void Sample::get()
{
    cin>>x;
    ++count;
}
static   void Sample::showCount(){    
    cout<<"Total No. of Objects :"<<count;
}
 int main()
{ Sample s1,s2;
    s1.get();
    s2.get();
    Sample::showCount();
   return 0;
}

编译错误:[Error]无法将成员函数"static void Sample::showCount(("声明为具有静态链接[-fpermission]

删除静态关键字

void Sample::showCount(){    
    cout<<"Total No. of Objects :"<<count;
}

类成员函数声明中的static关键字与函数定义中的static关键字具有不同的含义。前者告诉函数不需要类的实例(不获取this指针(,后者定义静态链接:对于文件是本地的,函数只能在这个特定文件中访问。

您还缺少计数的定义你需要在main:之前的某个地方挂一条线

int Sample::count = 0;
...
main() {
...
}
class Sample
{ ...
    static void showCount();
};
static   void Sample::showCount(){    
    cout<<"Total No. of Objects :"<<count;
}
// You can void instead of static, because you are not returning anything.

这是不正确的。您不需要第二个static

在C++中声明静态成员函数时,只能在类定义中将其声明为static。如果您在类定义之外实现函数(就像您已经实现的那样(,请不要在那里使用static关键字。

在类定义之外,函数或变量上的static关键字意味着符号应该具有"静态链接"。这意味着它只能在其所在的源文件(翻译单元(中访问。当所有编译的源文件链接在一起时,static符号不共享。

如果你不熟悉术语"翻译单位",请参阅这个SO问题

Saurav Sahu提到了另一个问题:您声明了静态变量static int count;,但从未定义过它

int Sample::count = 0;
#include <iostream>
using namespace std;
class Sample
{
    int x;
public:
    static int count;
    void get();
    static void showCount();
};
int Sample::count = 0;
void Sample::get()
{
    cin >> x;
    ++count;
}
void Sample::showCount(){
    cout << "Total No. of Objects :" << count;
}
int main()
{
    Sample s1, s2;
    s1.get();
    s2.get();
    Sample::showCount();
    return 0;
}