繁体   English   中英

C ++中的类构造函数

[英]Class Constructor in C++

我正在尝试编写一个构造函数,该构造函数采用学生ID编号以及学生的姓氏和名字的可选参数。 如果未提供,则ID号默认为0,名字和姓氏都默认为空字符串。 我对构造函数是完全陌生的,所以我不知道我在做什么,但这是到目前为止的事情...

#include <iostream>
#include <cstdlib>
#include <string>


class Student
{
public:
    Student(int idnumber, string fname, string lname);

由于某种原因,它的说法字符串未定义? 另外,如果没有提供信息,我是否可以使用一对if语句将ID缺省设置为0,将名称命名为空字符串? 请尽量让我无所事事,因为我对C ++非常陌生。 谢谢你的时间。

这是我正在使用的数据...所有名称和分数均已组成。

10601   ANDRES HYUN 88 91 94 94 89 84 94 84 89 87 89 91 
10611   THU ZECHER 83 79 89 87 88 88 86 81 84 80 89 81 
10622   BEVERLEE WAMPOLE 95 92 91 96 99 97 99 89 94 96 90 97 
10630   TRUMAN SOVIE 68 73 77 76 72 71 72 77 67 68 72 75 

您必须使用名称空间引用字符串类型,该名称空间为stdstd::string fname

您的示例如下所示:

#include <iostream>
#include <cstdlib>
#include <string>


class Student
{
public:
    Student(int idnumber = 0, std::string fname = "", std::string lname = "");

如果您想让自己变得非常拘束,可以将类型称为::std::string但是std::string通常就足够了(除非您要构建通用库)。

您需要先添加std:: 您可以using std::cout; 在顶部,然后像您一样使用cout

最后,您需要研究重载运算符。

class Myclass {
    MyClass() { /*set defaults here*/ }
    MyClass(int id, std::string fname, std::string lname) { /* Set values here*/ }
};

使用std::string

或者如果您不想一次又一次地写,只需写

using namespace std;

在主定义或类定义之前的全局范围内

#include <iostream>
#include <cstdlib>
#include <string>

using namespace std;

class Student
{
 public:
   Student(int idnumber, string fname, string lname);
class Student {
public:
    Student(int idnumber=0, std::string fname="", std::string lname="")
        : idnumber(idnumber), fname(fname), lname(lname) {}

private:
    int idnumber;
    std::string fname;
    std::string lname;
};

这使用参数默认值为未明确传递的参数指定默认值。然后,可以通过以下四种方式之一构造Student对象:

Student s1;                      // idnumber=0, fname="", lname""
Student s2(1);                   // idnumber=1, fname="", lname=""
Student s3(1, "John");           // idnumber=1, fname="John", lname=""
Student S4(1, "John", "Smith");  // idnumber=1, fname="John", lname="Smith"

然后,它使用初始化语法来相应地设置字段。

: idnumber(idnumber)

指定应使用参数idnumber的值初始化名为idnumber的类成员。 是的,它们可以使用相同的名称。 编译器知道您的意思。

构造函数本身的主体为空,因为它没有其他事情要做。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM