C++基础3(对象以及友元)
可变参数
参数个数不定,可以是任意多。可变参数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;
public :
static 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{
private:
int a;
}
class B {
A objA;
public:
void change (int num ){
objA.a = num
}
int getA(){
return objA.a;
}
}
// 无法修改 因为a是A私有的 所以B无法访问change和 getA会报错
//添加友元类即可 如下
class A{
public:
friend class B;//B 为A的友元类 可以访问a 的私有属性
private:
int a;
}