C++类里静态成员链接错误

  我现声明一个类内静态变量:

class test{
public:
    static int a;
    int get();
};

  在test.cpp中对a进行使用

#include<test.h>
int test::get()
{
    return a;                    
}

  会产生链接错误

 

   这可能是为了兼容c语言static只能在本文件起作用的特点而造成的。

  解决方案:

    ①在头文件中定义函数

    

#pragma once
class test
{
public:
	static int a;
	int get()
	{
		return a;
	}
};

    ②在源文件加上静态变量的声明

#include "test.h"

int test::a;

int test::get()
{
	return a;
}

 

  

 

posted @ 2022-03-03 20:21  帝皇の惊  阅读(232)  评论(0)    收藏  举报