马蓉的包包:C++程序源码

来源:百度文库 编辑:高校问答 时间:2024/04/28 02:22:57
class shared{
static int a;
int b;
public:
void set(int i,int j){a=i;b=j;}
void show();
};

void shared::show()
{
cout<<"This is static a :"<<a;
cout<<"\n This is non-static b:"<<b;
cout<<"\n";
}

main()
{
shared x,y;

x.set(1,1);
x.show();

y.set(2,2);
y.show();

x.show();

return 0;
}

在VC上编译出了两个错误
32.obj : error LNK2001: unresolved external symbol "private: static int shared::a" (?a@shared@@0HA)
Debug/3f.exe : fatal error LNK1120: 1 unresolved externals
Error executing link.exe.

3f.exe - 2 error(s), 0 warning(s)

请指教 谢谢

在你定义shared.cpp文件中加入int shared::a;这句就可以了,在类中定义的静态成员,一定要在CPP文件中实现一下。

很简单
一, 你缺少一个 include <iostream.h> (估计这个问题不大)

二, 之所以编译出错是因为你在定义类 shared 中 定义 a 为 static 类型
如果把static 去掉 即把 static int a; 变为 int a;
你在进行编译 应该不会出错了