#include <iostream>
#include <string>
using namespace std;
class Student {
public:
Student(const string& name1, int age1, int no1) {
name = name1;
age = age1;
no = no1;
}
private:
string name;
public:
int age;
int no;
void who(void) {
cout << "我叫" << name << endl;
cout << "今年" << age << "岁" << endl;
cout << "学号是:" << no << endl;
}
};
int main()
{
Student s("张三",25,10011); //在栈区创建单个对象格式一
//Student s 如果是无参--没有括号
s.who();
Student s1 = Student("李四", 26, 10012); //在栈区创建单个对象格式二
//单个参数时,后面的类名可以省略,比如:string str="liming"
s1.who();
//在栈区创建多个对象--对象数组
Student ss[2] = { Student("张三三",25,10013),Student("李四四",25,10014) };
ss[0].who();
Student* d = new Student("赵云", 29, 10015);//在堆区创建单个对象--对象指针
//new操作符会先分配内存再调用构造函数,完成对象的创建和初始化;而如果是malloc函数只能分配内存,不会调用构造函数,不具备创建对象能力
d->who();
delete d; //销毁单个对象
Student* p = new Student[2]{ //在堆区创建多个对象--对象指针数组
Student("刘备",40,10016),Student("刘彻",45,10017)
};
p[0].who();
delete[] p; //销毁
return 0;
}
原文链接: https://www.cnblogs.com/liming19680104/p/13488504.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/201454
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!