gpt4 book ai didi

用于类和结构之间交互的 C++ 语法

转载 作者:太空宇宙 更新时间:2023-11-04 14:30:37 25 4
gpt4 key购买 nike

我正在做 C++ 第一学期的作业,但我只是想不出它的工作语法。我需要使用指针将结构作为参数传递给类函数。我复制的这段代码是我最好的尝试,它可以编译,但在询问名字时会崩溃。当我尝试语法的变化时,我收到有关不完整结构、 undefined variable 的错误(warrior was 或无效运算符。我做错了什么?

#include <iostream>

using namespace std;

class StarWars
{
public:
int totalNumber;
struct data_clone
{
int ID, timeCounter;
string name;
};
data_clone *warrior;
void createClone()
{
cout << "How many clone warriors do you want to create in total?" << endl;
cin >> totalNumber;
}
void input(struct data_clone *pointer, int total)
{

for(int i = 1; i <= total; i++)
{
cout << "For warrior number " << i << ":" << endl;
cout << "What is the warrior's name?" << endl;
cin >> pointer[i].name;
cout << "What is the warrior's ID number?" << endl;
cin >> pointer[i].ID;
cout << "What is the warrior's time counter?" << endl;
cin >> pointer[i].timeCounter;
}
}
void lifeSpan(struct data_clone *pointer, int total)
{
for(int i = 1; i <= total; i++)
{
cout << "Warrior number " << pointer[i].name << ": " << endl;
while(pointer[i].timeCounter > 0)
{
cout << "Warrior name: " << pointer[i].name << endl;
cout << "Warrior ID number: " << pointer[i].ID << endl;
cout << "Warrior time counter: " << pointer[i].timeCounter << endl;
cout << "Clone is alive." << endl;
pointer[i].timeCounter--;
}
cout << "Warrior name: " << pointer[i].name << endl;
cout << "Warrior ID number: " << pointer[i].ID << endl;
cout << "Warrior time counter: " << pointer[i].timeCounter << endl;
cout << "Clone is dead." << endl;
}
}


};

int main(void)
{
StarWars clones;
clones.createClone();
clones.input(clones.warrior, clones.totalNumber);
clones.lifeSpan(clones.warrior, clones.totalNumber);
}

最佳答案

您没有初始化内存勇士指向的内存,因此您正在使用未初始化的内存 - 这总是一件坏事。这里有两件事要记住:

使用指针时,总是先初始化它们后面的内存。更喜欢使用 RAII 概念,如 std::unique_ptr/std::shared_ptr

void DoStuff(Widget* w);

std::unique_ptr<Widget> pw = std::make_unique<Widget>();
DoStuff(w.get());

使用普通变量时,使用解引用/引用运算符获取指向变量的指针。

void DoStuff(Widget* w);

Widget widget;
DoStuff(&w);

关于用于类和结构之间交互的 C++ 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35596329/

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