常数据成员(1)

常数据成员

#include <iostream>
using namespace std;
#include <cstring>

class person
{

public:
  const int age=80;//常数据成员可以在定义的时候初始化
  const string name;

public:
  person() ;
};

person::person():age(age),name(name)//常数据成员也可以使用初始化列表初始化.
{
    //但是不能在构造函数内使用赋值的方式初始化
  cout<<age<<endl;
  cout<<this->age<<endl;
cout<<"调用构造函数"<<endl;
}

int main()
{

  person *boy = new person();
  cout << "m_age: " << boy->age << endl;
}

常函数

#include <iostream>
#include <cstring>
using namespace std;
char a;
class person
{
private:
  int age;
  string name;
  const int age_f;
  const string name_f;
  // char *pointer = nullptr;//这样会导致空指针赋值
  char *pointer;

public:
  person(int age = 0, string name = "aa", int age_f = 2, string name_f =    "bb");
                  
  void print();

  void print_f(char *) const;
};

person::person(int age, string name, int age_f, string name_f) : age(age), name(name), age_f(age_f), name_f(name_f)
{                                         //这里通过缺省参数,实现了对const数据成员的初始化,实际上也就算是初始化列表
  pointer = new char[20];    
  cout << "aaaaaaaa" << endl;
};
// string类封装好了,不存在浅拷贝。
void person::print() //非const成员函数可以调用const和非const
{
  cout << "age:" << age << "name:" << name << endl;
  cout << "age_f:" << age_f << "name_f:" << name_f << endl;
};
void person ::print_f(char *new_pointer) const
{
  // pointer=new_pointer;//这样是不被允许的

  //   //如果是需要拷贝数据的话,先得给pointer 分配空间(由于这里是const函数,所以我把空间分配放到构造函数里去)再memcpy 或者strcpy

  strcpy(pointer, new_pointer);                             //这样是被允许的只改变值   //  *pointer=*new_pointer;
  cout << "age_f:" << age_f << "name_f:" << name_f << endl; // const成员函数只能 调用const成员,不能调用非const成员。
  // cout << "age:" << age << "name:" << name << endl;

  // 若将成员函数声明为const,则不允许通过其修改类的数据成员。
  // 值得注意的是,如果类中存在指针类型的数据成员即便是const函数只能保证不修改该指针指向的对象,也就是指针变量名不被允许修改,并不能保证不修改指针指向的值,也就是*pointer可被修改。
};
int main()
{
  const person *boy = new person(); //定义常对象;常对象只能调用常函数

  char *pointer = (char *)"aabbccdd";
  boy->print_f(pointer);

  char *ppointer = (char *)"plmplm";
  person *gril = new person();
  gril->print();
  gril->print_f(ppointer);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

丁金金

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值