C++术语和简明的英语说明措辞

C++ terminology and plain English instructions phrasing

本文关键字:英语 说明 术语 C++      更新时间:2023-10-16

晚上好!

我是一名初级程序员,即将完成C++的第一个学期。目前,我正在看教授给我们的期末考试复习表,我只是不明白它到底要求我做什么。我觉得如果我看到一个例子,我会马上得到,但事实上,我很失落。

这是复习问题。

Problem: Given the following class definition, implement the class methods. 
class CreditCard {
  public:
    CreditCard(string & no, string & nm, int lim, double bal = 0);
    string getNumber();
    string getName();
    double getBalance();
    int getLimit();
    // Does the card have enough to buy something?
    bool chargelt(double price); 
  private:
    string number;
    string name;
    int limit;
    double balance;
}; 

我知道这里没有太多的上下文,但让我们只说,在这是一门C++入门课程的背景下,可能会要求我做什么/学习什么?我真的不确定"实现类方法"在这里意味着什么,虽然这可能是我已经看到的,但很可能这只是我没有用通俗英语理解它的问题。

我想也可以问:如果你用这个代码教一个初学者,你希望他们用它做什么或从中学习什么?

任何见解都将不胜感激=)

严格来说,C++语言没有"方法"。它有"成员函数",也许这是你更熟悉的术语。但许多其他语言确实使用"方法"一词,因此C++程序员在真正谈论成员函数时说"方法"实际上相当常见。

类定义显示该类定义了四个成员函数:

string getNumber();
string getName();
double getBalance();
int getLimit();

定义还表明有一个构造函数:

CreditCard(string & no, string & nm, int lim, double bal = 0);

构造函数也是一种成员函数,但大多数人不会将构造函数称为"方法"。不过,有些人可能会这样做。

因此,指令"实现类方法"意味着:"为成员函数getNumber() getName() getBalance()getLimit()编写代码。"

它也可能意味着"并为构造函数CreditCard(string & no, string & nm, int lim, double bal)编写代码"。

将信用卡视为现实世界中的对象。它将具有名称、编号、限制等属性。所以,你必须在构造函数方法中设置这些值,因为当我们创建信用卡时,我们会将这些值分配给它们,比如这个

CreditCard::CreditCard(string & no, string & nm, int lim, double bal = 0)
{
   this->number = no; //you can also use number = no
   this->limit = lim;
   this->name = nm;
   this->balance = bal;
}

现在,由于我们有一张信用卡,我们可能想知道卡的名称,所以这可以实现如下:

string CreditCard::getName();
{
    return name;
}

同样的方法,我们可以得到极限和数量。我会把它留给你。

这段代码是一个类的定义,一个对象的蓝图。它介绍了C++的强面向对象编程,并包含了一些关键概念。

你有一个基本对象的元素。

class CreditCard {
      public:
        // Constructor.(to construct an object).
        CreditCard(string & no, string & nm, int lim, double bal = 0);
        // Accessors (to access the attributes of the object).
        string getNumber();
        string getName();
        double getBalance();
        int getLimit();
        // Does the card have enough to buy something?
        /// A public method of the class.
        bool chargelt(double price); 
      private:
        // Attributes.
        string number;
        string name;
        int limit;
        double balance;
    }

术语实现意味着您必须创建为类定义的函数。通常,对于每个类,都会为定义制作一个头文件,为实现制作一个源文件,但也可以在同一页上制作。

一个方法的实现可以遵循这个模板:

string CreditCard::getNumber()
{
    return number; // Instructions as you're making a standard function.
}

对于构造函数,初始化对象的属性是很重要的。因此,在构造函数的实现中,必须将输入参数与属性相关联。请注意,您不需要返回任何值,因为创建的对象可以被视为"返回值"。