首页 > 解决方案 > 如何在静态成员函数中使用其他静态成员——C++

问题描述

下面我有一堂课

#include <iostream>

#include <vector>
using namespace std;

class Car
{

public:
static int b;


static char* x1(int x)
{
    b=x;
    return (char *)"done";
}

};

主要

int main()
{
    char* ret = Car::x1(42);
    for(int x=0;x<4;x++)
    {cout<<ret[x]<<endl;}
  
    return 0;
}

但我收到以下错误

/usr/bin/ld: /tmp/ccRfvgz8.o: warning: relocation against `_ZN3Car1bE' in read-only section `.text._ZN3Car2x1Ei[_ZN3Car2x1Ei]'
/usr/bin/ld: /tmp/ccRfvgz8.o: in function `Car::x1(int)':
main.cpp:(.text._ZN3Car2x1Ei[_ZN3Car2x1Ei]+0xc): undefined reference to `Car::b'
/usr/bin/ld: warning: creating DT_TEXTREL in a PIE
collect2: error: ld returned 1 exit status

更新

在 Serge Balesta 发表评论后,我将 x1 函数更改为包含 Car::b=x;,但出现此错误

/usr/bin/ld: /tmp/ccjMKe4u.o: warning: relocation against `_ZN3Car1bE' in read-only section `.text._ZN3Car2x1Ei[_ZN3Car2x1Ei]'
/usr/bin/ld: /tmp/ccjMKe4u.o: in function `Car::x1(int)':
main.cpp:(.text._ZN3Car2x1Ei[_ZN3Car2x1Ei]+0xc): undefined reference to `Car::b'
/usr/bin/ld: warning: creating DT_TEXTREL in a PIE
collect2: error: ld returned 1 exit status

更新功能

static char* x1(int x)
{
    Car::b=x;
    return (char *)"done";
}

标签: c++

解决方案


推荐阅读