gpt4 book ai didi

c++ - 给一个类访问另一个 C++

转载 作者:行者123 更新时间:2023-11-30 01:56:16 26 4
gpt4 key购买 nike

我正在尝试访问另一个类(class)中一个类(class)的成员。我是 C++ 的新手,如果这是一个简单的修复,请原谅我,但我找不到答案,所以我来到这里。

在这种情况下,我想调用“init();”来自类 CGuessNumber 和成员 CheckNumber。

这是我的代码。

#include <iostream>
#include <ctime>
#include <cstdlib>

class CGuessNumber
{
public:
int GenerateNumber()
{
return rand() % 100 + 1;
}

void checkNumber(int guess, int answer, int &attempts)
{

if (guess < answer)
{
std::cout << "TOO LOW, TRY AGAIN" << "\n" << "TRYS LEFT: " << attempts << "\n";
attempts--;
}else if(guess > answer)
{
std::cout << "TOO HIGH, TRY AGAIN" << "\n" << "TRYS LEFT: " << attempts << "\n";
attempts--;
}else if(guess == answer)
{
std::cout << "YOU WON!" << "\n" << "TRYS LEFT: " << attempts << "\n";
}

if (attempts <= 0)
{
std::cout << "YOU LOST!" << "\n" << "TRYS LEFT: " << attempts << "\n";
CGAME::init(answer, attempts);
}

}
}Number;

class CGAME
{
public:
void init(int &answer, int &attempts)
{
answer = Number.GenerateNumber();
attempts = 5;
};

int newGame()
{
srand (time(NULL));
int intAnswer, playerGuess, trys;

init(intAnswer, trys);

while(intAnswer != playerGuess and trys > 0)
{
std::cin >> playerGuess;

Number.checkNumber(playerGuess, intAnswer, trys);
}
};
}ONewGame;

int main()
{
CGAME ONewGame
ONewGame.newGame();

return 0;
}

最佳答案

我想,这就是你要找的东西

基本上,您可以将指向一个对象的指针传递给另一个对象的构造函数。在这种情况下,我们只是将指向 CGuessNumber 的指针传递给 CGAME 构造函数,我们还将此指针存储在一个私有(private)字段中,以便我们可以使用它。然后就可以使用这个指针来调用方法了。

working example (pointer->method syntax)

working example (reference.method syntax)

#include <iostream>
#include <ctime>
#include <cstdlib>

class CGuessNumber
{
public:

int GenerateNumber()
{
return rand() % 100 + 1;
}

void checkNumber(int guess, int answer, int &attempts)
{

if (guess < answer)
{
std::cout << "TOO LOW, TRY AGAIN" << "\n" << "TRYS LEFT: " << attempts << "\n";
attempts--;
}else if(guess > answer)
{
std::cout << "TOO HIGH, TRY AGAIN" << "\n" << "TRYS LEFT: " << attempts << "\n";
attempts--;
}else if(guess == answer)
{
std::cout << "YOU WON!" << "\n" << "TRYS LEFT: " << attempts << "\n";
}

if (attempts <= 0)
{
std::cout << "YOU LOST!" << "\n" << "TRYS LEFT: " << attempts << "\n";
}
}
};

class CGAME
{
public:

CGAME(CGuessNumber* pNumber)
{
m_number = pNumber;
}
void init(int &answer, int &attempts)
{
answer = m_number->GenerateNumber();
attempts = 5;
};

void newGame()
{
srand (time(NULL));
int intAnswer, playerGuess, trys;

init(intAnswer, trys);

while(intAnswer != playerGuess and trys > 0)
{
std::cin >> playerGuess;

m_number->checkNumber(playerGuess, intAnswer, trys);
}
};

private:
CGuessNumber* m_number;
};

int main()
{
CGuessNumber* pGnum = new CGuessNumber();
CGAME* ONewGame = new CGAME(pGnum);
ONewGame->newGame();
return 0;
}

关于c++ - 给一个类访问另一个 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19920745/

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