我有一个简单的程序,其中有两个类是Hat
和Person
。每个Person
都有一个string name
、 aint idNum
和一个 hat 对象。每个帽子只有一个字符串hatType
和一个字符hatSize
。在 main 方法中,我想简单地声明 2 个人并使用显示方法来显示信息。这是我当前的代码,请放轻松,我还是C++ 中OOP 的新手。
人物类
class Person
{
private:
string name;
unsigned int idNum;
Hat myHat;
public:
Person(string, unsigned int, Hat);
void display();
};
Person::Person(string personName, unsigned int personID)
{
name = personName;
idNum = personID;
myHat = hat;
}
void Person::display()
{
cout << "Given name : " << name << endl;
cout << "Id. number : " << idNum << endl;
hat.display();
}
帽子类
class Hat
{
private:
string hatType;
char hatSize; // S, M, L
public:
Hat(string,char);
void display();
};
Hat::Hat(string _type, char _size){
hatType = _type;
hatSize = _size;
}
void Hat::display()
{
cout << "Hat type : " << hatType << endl;
cout << "Hat size : " << hatSize << endl;
}
主要的
int main()
{
Person personA("Alice",12321, Hat("Trilbee",'M'));
Person personB("Bob",2324, Hat("Ferret",'S'));
personA.display();
personB.display();
return 0;
}
以下是完整的更正(工作)版本。我添加了一些评论以显示我所做的更改。
#include <iostream>
#include <string>
using namespace std;
class Hat
{
private:
string hatType;
char hatSize; // S, M, L
public:
Hat(string,char);
//Added this default constructor since it won't be synthesized automatically
Hat()
{
std::cout<<"Default constructor"<<std::endl;
}
void display();
};
Hat::Hat(string _type, char _size){
hatType = _type;
hatSize = _size;
}
void Hat::display()
{
cout << "Hat type : " << hatType << endl;
cout << "Hat size : " << hatSize << endl;
}
class Person
{
private:
string name;
unsigned int idNum;
Hat myHat;
public:
Person(string, unsigned int, Hat);
void display();
};
//added the 3rd parameter of type Hat
Person::Person(string personName, unsigned int personID, Hat hat)
{
name = personName;
idNum = personID;
myHat = hat;
}
void Person::display()
{
cout << "Given name : " << name << endl;
cout << "Id. number : " << idNum << endl;
myHat.display();//changed hat.display() to myHat.display();
}
int main()
{
Person personA("Alice",12321, Hat("Trilbee",'M'));
Person personB("Bob",2324, Hat("Ferret",'S'));
personA.display();
personB.display();
return 0;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句