在另一个类中使用一个类的静态对象

Use of static object of one class in the other

本文关键字:一个 静态 对象 另一个      更新时间:2023-10-16

我试图测试调用静态对象从一个类在另一个。我在这里得到链接错误LNK2001:未解析的外部符号"公共:静态类K G::ob1"我不知道出了什么问题,在互联网上我找不到任何关于静态对象的信息,只有静态与所有其他配置。因此,我请求你的帮助。我是否需要创建一个K的对象来让这个整体起作用,或者我是否可以抽象到不创建任何对象?

#include <iostream>
using namespace std;
class K
{
    int a;
public:
    K(int x) { a = x; };
    void print() {  cout << " a is: " << a << endl; };
};
class G
{
public:
    static K ob1;
    static void printG()
    {
        ob1.print();
    };
};
int main()
{
    K o1(10);
    G::printG();
    system("pause");
}

必须定义静态变量。它类似于c中的全局变量。

K G::ob1;
int main(){ .... }