C++基础3(对象以及友元)

本文深入探讨了C++中的高级特性,包括可变参数的使用方法、static关键字在类中的应用、const修饰符对成员函数的限制作用以及友元机制如何帮助访问类的私有成员。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

可变参数

参数个数不定,可以是任意多。可变参数va

int sum (int num,...){

//...为可变参数

       va_list vp;

       va_start(vp,num);

       int sum =0;

       for(int i=0;i<num;i++){

       num+=va_arg(vp,int)

       }

       va_end(vp);

       return sum;

}

 

static在类中的使用

class Student{
       private:

       char* name;

       int age ;

       static int tag;
       publicstatic void change(){

              tag += 12;
              //age = 24; //会报错 静态方法只能操作静态属性或学者方
       }

}
//需要在外部进行赋值 使用::

 

int Student::tag = 11;

 

void main(){
       Student::change();
       cout<<Student::tag<<endl;
} 

const 修饰函数

class Student{
private:

       char* name;

       int age ;

       static int tag;

public//无影响 可正常调用修改
       const void change_age(){
              age = 24;
              }
              //会报错 限制this关键字 不能对类的属性进行修改
              //相当于 this = const Student *const this;
              //第一个const 是常量指针 值不能修改
              //第二个const 是指针常量 地址不能修改
              //this 的默认是指针常量   this = Student *const this;
       void change_age()const {

              age = 24;

              }

} 

void main(){
       Student stu;
       stu.change();  

}

友元函数 和友元类

可以修改私有的属性
友元函数

class Student{
private:
       char* name;
       int age ;
       static int tag;
public//可以通过友元函数修改 age
       friend void change_age(Student* stu,int age){

              stu->age = age;

       }

}

友元类

class A{
privateint a;

}


class B {

       A objA;
     
publicvoid change (int num ){

              objA.a = num

       }
       int getA(){
              return objA.a;
       }

}

// 无法修改 因为a是A私有的  所以B无法访问change和 getA会报错

//添加友元类即可 如下

class A{

publicfriend class B//B 为A的友元类 可以访问a 的私有属性

privateint a;

}


 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值