[英]Classes and OOP help C++
I'm having trouble with a simple code I have to for class, I'm trying to figure out how to add in a user input into a class, I've tried multiple things and could really use some assistance.我在使用简单的代码时遇到了麻烦,我必须为课堂编写代码,我试图弄清楚如何将用户输入添加到类中,我已经尝试了多种方法,并且确实可以使用一些帮助。
Code so Far:到目前为止的代码:
#include <iostream>
#include <string>
using namespace std;
// Base class
class GameShow{
public:
string Name;
cout << "Enter name of constestant: ";
cin >> Name;
cout << "Welcome " << Name <<"! Let's get ready to play the FEUD!!" << endl;
};
// Derived class
class FamilyFued{
public:
points;
};
int main ()
{
GameShow TN;
TN.Name
return 0;
}
Classes are used to abstract the state and behavior of things.类用于抽象事物的状态和行为。 State is in the form of class attributes.
状态以类属性的形式存在。 The behaviour is in the form of class methods (functions).
行为以类方法(函数)的形式出现。
This is a behaviour:这是一种行为:
cout << "Enter name of constestant: ";
cin >> Name;
cout << "Welcome " << Name <<"! Let's get ready to play the FEUD!!" << endl;
So you need to put it inside a function:所以你需要把它放在一个函数中:
class GameShow{
public:
string Name;
GameShow(){
cout << "Enter name of contestant: ";
cin >> Name;
cout << "Welcome " << Name <<"! Let's get ready to play the FEUD!!" << endl;
}
};
Based on what you have, you might want to wrap cout >> ...; cin <<...;
根据您所拥有的,您可能想要包装
cout >> ...; cin <<...;
cout >> ...; cin <<...;
part in a constructor:参与构造函数:
class GameShow{
public:
string Name;
GameShow()
{
cout << "Enter name of constestant: ";
cin >> Name;
cout << "Welcome " << Name <<"! Let's get ready to play the FEUD!!" << endl;
}
};
Other than that, please refer to: The Definitive C++ Book Guide and List除此之外,请参考: The Definitive C++ Book Guide and List
You code missing too many basics, you need start with a good c++ book.你的代码缺少太多基础知识,你需要从一本好的 C++ 书开始。
using namespace std ; 使用命名空间 std ;
// is bad idea, mentioned in stack overflow thousands of times.
bad坏的
class GameShow{
public:
string Name;
cout << "Enter name of constestant: ";
cin >> Name;
cout << "Welcome " << Name <<"! Let's get ready to play the FEUD!!" << endl;
};
Your cout
and cin
function should be used inside a constructor您的
cout
和cin
函数应该在构造函数中使用
class GameShow{
public:
string Name;
GameShow()
{
std::cout << "Enter name of constestant: ";
std::cin >> Name;
std::cout << "Welcome "
<< Name
<< "! Let's get ready to play the FEUD!!" << std::endl;
}
}; };
TN.Name // what this line doing in your main function ??
Assuming you wanted to print Name
of GameShow
class member, so change your line to below.假设您想打印
GameShow
类成员的Name
, GameShow
您的行更改为下面。
std::cout << TN.Name;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.