#include <iostream>
struct Person{
Person()
{
m_id = 1;
}
Person(int id, int age):m_id(id), m_age(age){}
Person(int age):Person()// 委托Person()构造函数,运行同一个类中一个构造函数调用另一构造函数
{
m_age = age;
}
int m_id;
int m_age;
};
void test1()
{
Person p(10);
std::cout<<"p1.m_id:"<<p.m_id<<std::endl;
std::cout<<"p1.m_age:"<<p.m_age<<std::endl;
}
// 普通继承时构造函数
class Student:public Person{
public:
Student(int id, int age) : Person(id, age){}
};
void test2()
{
Student s(10, 20);
std::cout<<"s.m_id:"<<s.m_id<<std::endl;
std::cout<<"s.m_age:"<<s.m_age<<std::endl;
}
// 使用using 关键字 using进行继承构造
struct SubClass:Person
{
public:
using Person::Person;// 继承构造
};
void test3()
{
SubClass s(2);
std::cout<<"s.m_id:"<<s.m_id<<std::endl;
std::cout<<"s.m_age:"<<s.m_age<<std::endl;
}
int main()
{
test1();
test2();
test3();
return 0;
}
C++新特性委托和继承构造
最新推荐文章于 2024-07-19 11:42:48 发布