我在计算带有静态变量的对象总数的程序中出错
I have error in program to count total number of objects with static variable
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;
}
相关文章:
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- 内存清理程序报告全局对象构造中未初始化值的使用
- 程序如何'remember'临时对象?
- 什么是"undetectable means",它们如何更改 C/C++ 程序的对象?
- 是否可以使用非常量指针调用非常量函数,以及当两个unique_ptrs指向同一个对象时程序的行为方式?
- 将FFMpeg AVFrame对象从C++应用程序流式传输到Python的最佳方法?
- 将 C# 对象(包含静态对象成员)作为参数传递给 C++/CLI 程序
- C++,在对象内分配多个数据时,堆栈分配是否更有效? 在下面的程序中,类A_Heap的效率会更低吗?
- 通过 COM 对象连接 x64 应用程序时出现问题
- 修改多线程应用程序中的对象
- 无法在需要对象展开修复程序的函数中使用__try
- 在C++面向对象程序中,谁负责删除传递给构造函数的对象
- 将文件从 iOS 应用程序加载到 C++ 对象中/<iostream>iOS 上的问题
- 运行程序时找不到共享对象库,但在编译过程中链接了它
- 在C++中,系统如何将这些对象中的每一个与执行程序的窗口相关联?
- OpenGL和面向对象程序结构
- C++面向对象程序和PHP面向对象程序之间的区别
- C++面向对象程序中的获取和设置方法
- 我编写了一个小的面向对象程序,我不知道为什么它不能编译
- C++面向对象程序复制了继承模式