gpt4 book ai didi

C++从未定义的函数访问类

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:10:12 24 4
gpt4 key购买 nike

我是 C++ 的新手,在访问类中的变量时遇到了一些麻烦。到目前为止,从我在这里读到的内容来看,创建全局变量是一种非常糟糕的做法,而不是这样做,但我不知道还有什么方法可以移动对类的访问权限。

到目前为止,我的搜索指向我在类中设置和获取函数,但我认为我只能在定义对象的 block 中使用它们。

基本上我想知道的是,如果我在 main() 中定义一个类对象,然后在 main 中调用一个函数,例如 gameLoop(),我如何在不使类对象成为全局对象的情况下访问该新函数中的该对象。

例如:

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

class Word
{
private:
string m_word;
int m_length;
public:
void set(string word, int length)
{
m_word = word;
m_length = length;
}
};

void gameLoop()
{
word1.set(); //flags error as it cant acces the word1 object
//I want to be able to access word1 from here
//Not a copy because that wouldnt change the actual word1
//I dont want to define it in here because then it would be created again
//for each loop of gameLoop
}

int main()
{
Word word1;
int play = 1;
while (play ==1){
gameLoop();
}
return 0;
}

这是一个大大简化的版本,但为了游戏的目的,我希望类存储在外部,但 gameLoop 中的一些游戏功能能够访问和更改类对象。

最佳答案

理想情况下,函数的依赖项应该在参数列表中有说明。如果您的 gameLoop 函数需要一个 Word 对象,请将其作为参数传入。这样,函数需要哪些对象才能工作就一目了然了。这看起来像:

void gameLoop(Word& word)
{
word.set();
// ^ Obviously you need to supply args here.
}

int main()
{
Word word1;
int play = 1;
while (play ==1){
gameLoop(word1);
}
return 0;
}

并且由于您要在函数中改变 Word 对象,因此需要通过引用传递它,否则您只是在修改一个拷贝。

你唯一明智的选择是使单词 object 全局化,但应该不惜一切代价避免这种情况。它使测试变得更加困难,因为您需要考虑可能发生的每一个变化,这使得隔离问题变得困难。

关于C++从未定义的函数访问类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42979859/

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