在具体示例中使用指针

时间:2018-01-10 16:12:55

标签: c++ pointers

我理解指针的概念以及它们的工作原理。 但是我很难理解在哪个例子中我应该使用它们以及我可以在哪里使用变量。

免责声明:在创建这篇文章之前,我在类似的问题上阅读了很多答案,但答案是没有具体的例子。

以下是我的示例:假设我想创建一个类Course,该构造函数具有参与此课程的学生名称和列表。

我想实现的方法:

1)为每个学生保存测试结果并计算平均专业课程和专业学生。

2)为每个学生定义id_number(matr_num)和名称的方法。

为了实现这个类,我首先决定创建类Student

#include <iostream>
#include <vector>
#include <string>
#include <stdexcept>
#include <algorithm>
#include <cmath>
#include <list>
using namespace std;




class Student{
    private:
    string name;
    int matr_num;
    int test_1;
    int test_2;

    public:
    //Constructor:
    Student(string name,int matr_num,int test_1,int test_2);
    //Destructor:
    ~Student();
    //Copy constructor:
    Student(const Student& other);
    //Copy assingment:
    Student operator=(const Student& other);
    //Move constructor:
    Student(Student&& other);
    //Move assingment:
    Student operator=(Student&&other);  
    //Average of two tests:
    double test_average();
    //get name,matrikel_number, scores of test:
    string get_name() const ;
    double get_matr_num() const;
    double get_test_1() const ;
    double get_test_2() const ;

};

//Constructor
Student::Student(string name,int matr_num,int test_1,int test_2)
    :name{name},matr_num{matr_num},test_1{test_1},test_2{test_2}
        {
        }

//Destructor
Student::~Student(){
}

//Copy constructor:
Student::Student(const Student& other)
    :name{other.name},matr_num{other.matr_num},test_1{other.test_1},test_2{other.test_2}
        {

        }


//Copy assingment:
Student Student::operator=(const Student& other)
{
    name = other.name;
    matr_num = other.matr_num;
    test_1 = other.test_1;
    test_2 = other.test_2;

}   


//Move Constructor:
Student::Student(Student&& other)
    :name{other.name},matr_num{other.matr_num},test_1{other.test_1},test_2{other.test_2}
        {
            other.name = "";
            other.matr_num = 0;
            other.test_1 = 0;
            other.test_2 = 0;
        }       

//Move assingment:
Student Student::operator=(Student&& other)
{
    name = other.name;
    matr_num = other.matr_num;
    test_1 = other.test_1;
    test_2 = other.test_2;
    other.name = "";
    other.matr_num = 0;
    other.test_1 = 0;
    other.test_2 = 0;
}   

double Student::test_average(){
    return (test_1 + test_2)/2;
}


string Student::get_name()const{return name;}
double Student::get_matr_num()const{return matr_num;}
double Student::get_test_1()const{return test_1;}
double Student::get_test_2()const{return test_2;}

如你所见,我没有指针就这样做了,我会用它来创建课程Course

以下是问题:

1)我应该使用指针而不是变量吗?

2)如果是/否,为什么?在这种情况下使用指针的优点是什么?

0 个答案:

没有答案