概要
回顾了C++,学习了Go,栗子大意是根据输入输出,多次输入过后给出结果。
比较
C++:1-2头文件定义使用哪些库,3指定命名空间,8-21创建基类,22-37创建派生类,38-last主函数。C++标准输入输出库iostream,cin输入cout输出。类中包括成员变量和成员方法。
go:1指定包,3-6指定函数库,go中没有类的概念,13-16定义结构体,19结构体嵌套,24-44主函数。25-26初始化结构体,46-last定义结构体成员方法。
感觉Go写起来更像Python一些,Go没有了类的概念感觉很特别,保留了C++的结构体和指针,Go不需要写分号标识一句话的结束(Python也是),Go的转型应该是像C++的需要手动(39-40)。
代码
C++实现
#include <iostream>
#include <string>
using namespace std;
/**
故事概要:
你是一个好人吗? 请回答是或者不是
**/
class Info
{
public:
string answer;
string question;
string good_answer;
string bad_answer;
Info()
{
question = "Are you a good man? Answer me yes or no, please";
good_answer = "You are great, god bless you";
bad_answer = "oh, really stupid";
}
};
class GameInfo: public Info
{
public:
void printResult(int i)
{
cout << i << endl;
if (i >= 3)
{
cout << "game over, you lost" << endl;
}
else
{
cout << "game over, you win" << endl;
}
}
};
int main()
{
GameInfo gameInfo;
for (int i = 0; i < 3; i++)
{
cout << gameInfo.question << endl;
cin >> gameInfo.answer;
if (gameInfo.answer == "yes")
{
cout << gameInfo.good_answer << endl;
break;
}
else if(gameInfo.answer == "no")
{
cout << gameInfo.bad_answer << endl;
break;
}
else
{
cout << "bad answer, try again please" << endl;
cout << "you left " << 2-i << " times"<< endl;
}
}
gameInfo.printResult(i);
return 0;
}
Go实现
package main
import (
"fmt"
"strconv"
)
/**
故事概要:
你是一个好人吗? 请回答是或者不是
*/
type BaseInfo struct {
answer string
question string
}
type GameInfo struct {
BaseInfo
goodAnswer string
badAnswer string
}
func main() {
gameInfo := &GameInfo{BaseInfo{question:"Are you a good man? Answer me yes or no, please\n"},
"You are great, god bless you\n", "oh, really stupid\n"}
var i int = 0
for ; i < 3 ; i++ {
fmt.Print(gameInfo.question)
fmt.Scanln(&gameInfo.answer)
if gameInfo.answer == "yes"{
fmt.Println(gameInfo.goodAnswer)
break;
}else if gameInfo.answer == "no"{
fmt.Println(gameInfo.badAnswer)
break;
} else {
fmt.Println("bad answer, try again please")
time:= strconv.Itoa(2-i)
fmt.Println( "you left " + time + " times")
}
}
gameInfo.printResult(i);
}
func (gameInfo *GameInfo)printResult(i int) {
if i >= 3 {
fmt.Println("game over, you lost")
}else {
fmt.Println("game over, you win")
}
}