gpt4 book ai didi

不允许使用 C++ 数据成员初始值设定项

转载 作者:可可西里 更新时间:2023-11-01 15:41:30 26 4
gpt4 key购买 nike

我对 C++ 完全陌生,所以请多多包涵。我想创建一个带有静态数组的类,并从 main 访问这个数组。这是我想在 C# 中执行的操作。

   namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Class a = new Class();
Console.WriteLine(a.arr[1]);

}
}
}

=====================

namespace ConsoleApplication1
{
class Class
{
public static string[] s_strHands = new string[]{"one","two","three"};
}
}

这是我尝试过的:

// justfoolin.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;

class Class {

public:
static string arr[3] = {"one", "two", "three"};
};


int _tmain(int argc, _TCHAR* argv[])
{
Class x;
cout << x.arr[2] << endl;
return 0;
}

但是我得到了:IntelliSense:不允许数据成员初始值设定项

最佳答案

稍后需要进行初始化;您不能在类定义中初始化类成员。 (如果可以,那么在头文件中定义的类将导致每个翻译单元定义自己的成员拷贝,从而使链接器陷入困惑。)

class Class {
public:
static string arr[];
};

string Class::arr[3] = {"one", "two", "three"};

类定义定义了接口(interface),它与实现是分开的。

关于不允许使用 C++ 数据成员初始值设定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10936009/

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