#include <iostream>
//对象特征-初始化列表
using namespace std;
class person
{
public:
//传统方法
/* person(int a,int b,int c)
{
m_a=a;
m_b=b;
m_c=c;
}*/
//直接赋初值
//person():m_a(10),m_b(20),m_c(30){};
//可自由赋值
person(int a,int b,int c):m_a(a),m_b(b),m_c(c){};
int m_a;
int m_b;
int m_c;
};
/*void test01()
{
person p(10,20,30);
cout<<p.m_a<<" "<<p.m_b<<" "<<p.m_c<<endl;
/*person (10,20,30);
cout<<a<<b<<c<<endl;*/
void test02()
{
person p(1,2,3);
cout<<p.m_a<<p.m_b<<p.m_c<<endl;
}
int main()
{
test02();
return 0;
}
类对象作为类成员
#include <iostream>
#include<string>
//类对象作为类成员
using namespace std;
class phone
{
public:
Phone(string pname)
{
m_pname=pname;
}
string m_pname;
};
class person
{
public:
//phone m_phone=pname;//隐式转换法
person(string name,string pname):m_name(name),m_phone(pname)
{
}
string m_name;
phone m_phone;
};
void test01()
{
person p("zhangsan","oppo");
cout<<p.m_name<<p.m_phone.m_pnam<<endl;
}
int main()
{
test01();
return 0;
}
#include <iostream>
using namespace std;
class person
{
public:
static void func()
{
cout<<"静态函数调用中"<<endl;
};
};
void test01()
{
//1.通过对象访问
/*person p;
p.func();*/
//2.通过类名访问
person::func();
}
int main()
{
test01();
return 0;
}
静态成员函数
#include <iostream>
using namespace std;
class person
{
public:
static void func()
{
m_a=100;//静态成员函数可以访问静态成员变量
m_b=200;//静态成员函数不可以访问非静态成员变量
cout<<"静态函数调用中"<<endl;
};
static int m_a;//静态成员变量
int m_b;//非静态成员变量
//静态成员函数也是有访问权限的
private:
static void func2()
{
cout<<"func2调用"<<endl;
}
};
int person::m_a=0;//静态成员变量赋值
void test01()
{
//1.通过对象访问
/*person p;
p.func();*/
//2.通过类名访问
person::func();
person::func2();//类外访问不到私有静态成员函数
}
int main()
{
test01();
return 0;
}