gpt4 book ai didi

c++ - 类中的静态函数和数组

转载 作者:行者123 更新时间:2023-11-28 02:53:20 25 4
gpt4 key购买 nike

我在尝试编译下面的代码时遇到了 5 个错误。就像:它们主要指向 static string rzymstatic int arab。主要错误: 在 arab2rzym 函数中:

 - : invalid use of member ‘RzymArab::arab’ in static member function
- : error: from this location
- : error: invalid use of member ‘RzymArab::arab’ in static member function
- : invalid use of member ‘RzymArab::rzym’ in static member function
- : cannot declare member function ‘static std::string RzymArab::arab2rzym(int)’ to have static linkage [-fpermissive]

代码如下:

#include <iostream>
#include <string>

using namespace std;

class RzymArab
{
private:
string rzym[13] = {"I","IV","V","IX","X","XL","L","XC","C","CD","D","CM","M"};
int arab[13] = {1,4,5,9,10,40,50,90,100,400,500,900,1000};
public:
static int rzym2arab(string);
static string arab2rzym(int);
};

static string RzymArab::arab2rzym(int x)
{
int i=12;
string s="";

while(x>=1)
{
if(x>=arab[i])
{
x-=arab[i];
s=s+rzym[i];
}
else
i-=1;
}
return s;
}

int main()
{
string x;
x=RzymArab.arab2rzym(1164);
cout<<x<<endl;
return 0;
}

如果能提供帮助,我将不胜感激!我做了一些事情,但仍然有很多错误。我想在不创建对象的情况下使用类中的元素。有什么想法吗?

最佳答案

您不能从静态成员函数访问非静态类成员变量。您还需要将它们设为静态:

class RzymArab {
private:
static string rzym[13];
static int arab[13];
public:
static int rzym2arab(string);
static string arab2rzym(int);
};

还有那些需要单独定义(通常在你的类的.cpp文件中):

string RzymArab::rzym[13] = 
{"I","IV","V","IX","X","XL","L","XC","C","CD","D","CM","M"};
int RzymArab::arab[13] = {1,4,5,9,10,40,50,90,100,400,500,900,1000};

另外请注意,您不要使用 static 关键字作为静态函数的(非内联)定义(这是无效语法)。只写:

string RzymArab::arab2rzym(int x) {
// ...
}

查看完全修复、可编译和运行的示例 here请。

关于c++ - 类中的静态函数和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22584437/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com