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

11 篇文章 0 订阅

一、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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值