c++类分配内存和类指针

2022-08-10 12:16:39

一、C++中类指针的运用

1、类的指针(指向类的指针)

#include <iostream>

using namespace std;


class Box
{
public:
    // 构造函数定义
    Box(double l = 2.0, double b = 2.0, double h = 2.0)//定义缺省参数
    {
        cout << "Constructor called." << endl;
        length = l;
        breadth = b;
        height = h;
    }

    double Volume() //计算这个box的体积
    {
        return length * breadth * height;
    }

private:
    double length;     // Length of a box 长度
    double breadth;    // Breadth of a box 宽度
    double height;     // Height of a box  高度
};

int main(void)
{
    Box Box1(3.3, 1.2, 1.5);    // Declare box1,自定义第一个对象
    Box Box2(8.5, 6.0, 2.0);    // Declare box2,自定义第二个对象
    Box *ptrBox;                // Declare pointer to a class. 定义类的指针

    // 保存第一个对象的地址
    ptrBox = &Box1;

    // 现在尝试使用成员访问运算符来访问成员
    cout << "Volume of Box1: " << ptrBox->Volume() << endl;

    // 保存第二个对象的地址
    ptrBox = &Box2;

    // 现在尝试使用成员访问运算符来访问成员
    cout << "Volume of Box2: " << ptrBox->Volume() << endl;
    while (1);
    return 0;
}

以上通过函数的代码的角度分析定义了类的指针

参考博客:https://www.runoob.com/cplusplus/cpp-pointer-to-class.html

二、c++中给类分配内存,进行初始化

类的对象建立分为两种,一种是静态建立,一种是动态建立。

1、C++中静态建立

A a;  ====A为类,a为对象

2、C++中动态的建立

A* ptr=new A  ====A为类,ptr为对象指针

以下就是动态的分配内存

#include<iostream>
#include<string>

using namespace std;

class  student
{
public:
    string name;
    int age;
    void sayhello();
};

void student::sayhello()
{
    cout << "my name is: " + this->name + " I am: " << this->age;
    cout << "\n";
}


student* setname(string name)
{
   // student *stu = new student();

    student *stu;
    stu = new student();
    stu->age = 12;
    stu->name = name;
    return stu;
}

int main()
{
    student *p = setname("tom");
    p->sayhello();
    delete p;
    while (1);
    return 0;
}

 参考博客:https://www.cnblogs.com/xiaoxiaoqiang001/p/5557704.html

  • 作者:Littlehero_121
  • 原文链接:https://blog.csdn.net/Littlehero_121/article/details/98495272
    更新时间:2022-08-10 12:16:39