读书人

这段程序为什么会出错?该如何处理

发布时间: 2012-02-14 19:19:19 作者: rapoo

这段程序为什么会出错?
如题,程序如下:
#include <iostream>

using namespace std;

class test
{
static int aa;
public:
friend void setaa();
int getaa();
};
void setaa()
{
test::aa = 10000;
}
int test::getaa()
{
return aa;
}
int main()
{
int aaa; //用来暂停程序

test te;

cout < < te.getaa();

setaa();

cout < < te.getaa();

cin > > aaa; //用来暂停程序
}

下面的程序,将友元改为了静态成员函数,仍然出这个错误

#include <iostream>

using namespace std;

class test
{
static int aa;
public:
static void setaa();
int getaa();
};
void test::setaa()
{
test::aa = 10000;
}
int test::getaa()
{
return aa;
}
int main()
{
int aaa; //用来暂停程序

test te;

cout < < te.getaa();

test::setaa();

cout < < te.getaa();

cin > > aaa; //用来暂停程序
}

错误信息:链接错误:无法解析的外部符号“Private static int test::aa”

友元和静态成员的用法不是这样么?

[解决办法]
在 main 前加
int test::aa = 10000;

[解决办法]
第一段程序改为:

class test
{
static int aa;
public:
friend void setaa();
int getaa();
};
int test::aa;   //这里要加上对静态成员变量的义务初始化,后面再解释
void setaa()
{
test::aa = 10000;
}
int test::getaa()
{
return aa;
}
int main()
{
int aaa; //用来暂停程序

test te;

cout < < te.getaa();

setaa();

cout < < te.getaa();

cin > > aaa; //用来暂停程序
}


第二段也同样改为:

class test
{
static int aa;
public:
static void setaa();
int getaa();
};
int test::aa;        //这里要加上对静态成员变量的义务初始化,
void test::setaa()
{
test::aa = 10000;
}
int test::getaa()
{
return aa;
}
int main()
{
int aaa; //用来暂停程序

test te;

cout < < te.getaa();

test::setaa();

cout < < te.getaa();

cin > > aaa; //用来暂停程序
}


类的静态数据成员必须在类的体外进行显式的初始化,因为静态变量在编译的时候就要让编译器知道它的值,所以它的初始化一定要在类外,像一个成员函数的定义一样.

上面写的int test::aa;这相当于把aa先初始化为了0,再运行程序是对它的再赋值,而不是初始化了
[解决办法]
你需要对 类的 static 成员初始化一下:

int main()之前:

int test::aa = ??;

读书人网 >C++

热点推荐