类对象作为类成员
C++类中的成员可以是另一个类的对象,我们称该成员为 对象成员
例如:
class A {}
class B
{
A a;
}
B类中有对象A作为成员,A为对象成员
那么当创建B对象时,A与B的构造和析构的顺序是谁先谁后?
示例:
class Phone
{
public:
Phone(string name)
{
m_PhoneName = name;
cout << "Phone构造" << endl;
}
~Phone()
{
cout << "Phone析构" << endl;
}
string m_PhoneName;
};
class Person
{
public:
//初始化列表可以告诉编译器调用哪一个构造函数
Person(string name, string pName) :m_Name(name), m_Phone(pName)
{
cout << "Person构造" << endl;
}
~Person()
{
cout << "Person析构" << endl;
}
void playGame()
{
cout << m_Name << " 使用" << m_Phone.m_PhoneName << " 牌手机! " << endl;
}
string m_Name;
Phone m_Phone;
};
void test01()
{
//当类中成员是其他类对象时,我们称该成员为 对象成员
//构造的顺序是 :先调用对象成员的构造,再调用本类构造
//析构顺序与构造相反
Person p("张三" , "苹果X");
p.playGame();
}
int main() {
test01();
system("pause");
return 0;
}
#include <iostream>
#include <string>
using namespace std;
class Phone {
public:
Phone(string initPhoneName):phoneName(initPhoneName) {};
string phoneName;
};
class Person {
public:
Person(string initPersonName, string initPhoneName) :personName(initPersonName), phone(initPhoneName) {};
string personName;
Phone phone;
};
void example() {
Person p("John", "iPhone");
cout << p.personName << " has a(an) " << p.phone.phoneName << endl;;
}
int main()
{
example();
}
在java的控制台输出中有这样的语句:
System.out.println("Hello World!");
而利用面向对象编程思想中的类嵌套我们就可以在C++中实现这样的风格。
#include <iostream>
#include <string>
using namespace std;
class output {
public:
output() {};
void println(string STD_OUT) {
cout << STD_OUT << endl;
}
void print(string STD_OUT) {
cout << STD_OUT;
};
};
class Sysfunc {
public:
Sysfunc(){}
output out;
};
void example() {
Sysfunc System;
System.out.println("Hello World!");
cout << "This is how the Java's OUTPUT looks like" << endl;
System.out.print("Hello World!");
}
int main()
{
example();
//In java, we have a hello world program
//System.out.println("Hello World!");
}