C/C++基础知识(二)——类的构造

2019-10-12  本文已影响0人  王志强_9380

类的构造

.h的重复引入问题

创建一个.h文件(student.h)

#pragma once

这个代码的意思是防止重复引入.h文件,有的编译器不支持这个,所以我们可以使用#ifndef的方式来避免重复引入的问题

#pragma once
#ifndef  Student_H

#define Student_H
class Student {
}
#endif
构造函数和析构函数
class Student {
    int i;
public:
    Student();
    Student(int i);
    Student(int i, int j);
    ~Student();
private:
    int j;
};

创建student.cpp,实现构造方法

#include "student.h"
#include<iostream>
using namespace std;

Student::Student() {
    cout << "构造方法" << endl;
}

Student::Student(int a) :i(a) { //这种写法只能是构造函数
    cout << this->i << endl;
}

Student::Student(int i, int j) {
    this->i = i;
    cout << this->i << endl;
}

Student::~Student() {
    cout << "析构方法" << endl;
}

在main.cpp中调用构造方法

#include <iostream>
#include "Student.h"
int main()
{
    Student student;
    Student student1(55);
    Student student2(123, 234);
    std::cout << "hello world\n";
}

输出结果

构造方法
55
123
hello world
析构方法
析构方法
析构方法

注意

  • Student::Student(int a) :i(a)这种写法只能是构造函数中,普通函数会报错
  • public、private、protect等作用域是写在一块的,和java中不一样
常量函数

常量函数使用const修饰

student.h

class Student {
public:
    Student();
    ~Student();
    void setJ(int j);
    void setJ_const(int j) const;
private:
    int j;
};
student.cpp

void Student::setJ(int j) {
    this->j = j;
}

void Student::setJ_const(int j) const {
    //this->j = j; 
}

const修饰的函数不能够修改类的成员变量,只能够取值或者做一些逻辑判断

友元函数

如果在main.cpp中,想要修改Student类中的私有变量,普通的赋值是会报错的,这时候就可以使用友元函数
例:在main.cpp中定义一个方法

void frenedTest(Student* student) {
    student->j = 999;
}

会报错显示:变量不可访问,我们在Student中使用关键字friend定义一个友元函数

friend void frenedTest(Student*);

就可以访问私有变量了
如果有很多个方法要定义为友元函数,可以定义一个友元类

student.h

class Teacher
{
public:
    void call(Student* student) {
        student->j = 12345;
    }

    void call2(Student* student) {
        student->j = 67890;
    }
private:

};

然后Student类中声明该类为友元类

friend class Teacher;

然后就可以在main.cpp中访问到student的私有变量了

Teacher teacher;
teacher.call(&student);
teacher.call2(&student);

tips:

上一篇 下一篇

猜你喜欢

热点阅读