C++静态关键字问题4

预测以下C++程序的输出。

null

#include <iostream>
using namespace std;
class A
{
private :
int x;
public :
A( int _x)  {  x = _x; }
int get()  { return x; }
};
class B
{
static A a;
public :
static int get()
{ return a.get(); }
};
int main( void )
{
B b;
cout << b.get();
return 0;
}


(A) 0 (B) 链接器错误:未定义的引用B::a (C) 链接器错误:无法访问静态链接 (D) 链接器错误:多个同名函数get() 答复: (B) 说明: 由于B中未定义静态成员a,因此出现编译器错误。

要修复错误,我们需要显式定义a。以下程序运行良好。

#include <iostream >
using namespace std;

class A
{
private:
    int x;
public:
    A(int _x)  {  x = _x; }
    int get()  { return x; }
};

class B
{
    static A a;
public:
   static int get()
   {  return a.get(); }
};

A B::a(0);

int main(void)
{
    B b;
    cout << b.get();
    return 0;
}

这个问题的小测验

© 版权声明
THE END
喜欢就支持一下吧
点赞14 分享