undefined reference to `sth‘; collect2: ld returned 1 exit status

文章讨论了C++中static成员函数和静态数据成员的特性,指出它们在不同对象间共享同一份数据。通过一个示例代码展示了如何使用static变量,并解释了编译错误的原因是static变量未初始化。解决方案是在类定义外部对static变量进行初始化。
摘要由CSDN通过智能技术生成

学习c++中static 的用法如下:

Static member functions in C++ are the functions that can access only the static data members. These static data members share a single copy of themselves with the different objects of the same class.

写了下面的代码进行一个小测试。

# include <iostream>
using namespace std;

// test static in class

class TestStatic {
public: 
    static int a;
    int b;

    TestStatic() {
        b = 0;
        a = 6;
    }

    static void print() {
        cout << a << endl;
    }

    static void set(int b) {
        a = b;
    }
};

int main() {
    TestStatic a ;
    TestStatic b ;
    a.print();
    b.print();
    a.set(10);
    a.print();
    b.print();
    return 0;
}

发现编译时出现错误:

undefined reference to `TestStatic::a';

collect2: ld returned 1 exit status

原来这是因为static变量没有初始化。由于不能直接在类定义时进行初始化,可以在类定义后进行初始化赋值,修改后如下:

# include <iostream>
using namespace std;

// test static in class

class TestStatic {
public: 
    static int a;
    int b;

    TestStatic() {
        b = 0;
        a = 6;
    }

    static void print() {
        cout << a << endl;
    }

    static void set(int b) {
        a = b;
    }
};

int TestStatic::a = 5;
// this line is used to initialize the static variable

int main() {
    TestStatic a ;
    TestStatic b ;
    a.print();
    b.print();
    a.set(10);
    a.print();
    b.print();
    return 0;
}

程序能够正常编译运行:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值