c++设计与编程之包含关系(包容关系)
在使用包含内容的时候,对于表示类X的对象,存在着两种主要的可选方式:www.1生命一个类型为X的成员
2生命一个类型为X*或者X&的成员
如果指针值绝不改变,那么除了效率问题和写构造函数,析构函数的方式之外,这些选择方案是完全等价的:
class X{
public:
X(int);
};
class C{
X a;
X *p;
X &r;
public:
C(int i,intj,int k):a(i),p(new X(j)),r(*new X(k)){}
~C(){delete p;delete &r;}
}
1包含指针
[cpp] view plaincopyprint?
#include<iostream>
#include<string>
using namespace std;
class Person{
public:
Person(string name,int age){
this->name=name;
this->age=age;
}
Person(){}
virtual void show(){
cout<<name<<" "<<age;
}
private:
string name;
int age;
};
class Student{
public:
Student(string name,int age,string number1):p(new Person(name,age)),number(number1){}
Student(){}
void show(){
p->show();
cout<<" "<<number<<endl;
}
private:
string number;
Person *p;
};
int main(){
Student s("zhang",22,"091150");
s.show();
system("pause");
return 0;
}
<SPAN style="BACKGROUND-COLOR: #ffffff; FONT-FAMILY: Arial"></SPAN>
2包含对象
[cpp] view plaincopyprint?
#include<iostream>
#include<string>
using namespace std;
class Person{
public:
Person(string name,int age){
this->name=name;
this->age=age;
}
Person(){}
virtual void show(){
cout<<name<<" "<<age;
}
private:
string name;
int age;
};
class Student{
public:
Student(string name,int age,string number1):p(name,age),number(number1){}
Student(){}
void show(){
p.show();
cout<<" "<<number<<endl;
}
private:
string number;
Person p;
};
int main(){
Student s("zhang",22,"091150");
s.show();
system("pause");
return 0;
}
<SPAN style="BACKGROUND-COLOR: #ffffff; FONT-FAMILY: Arial"></SPAN>
3包含引用
[cpp] view plaincopyprint?
#include<iostream>
#include<string>
using namespace std;
class Person{
public:
Person(string name,int age){
this->name=name;
this->age=age;
}
Person(){}
virtual void show(){
cout<<name<<" "<<age;
}
private:
string name;
int age;
};
class Student{
public:
Student(string name,int age,string number1):number(number1),p(*new Person(name,age)){}
Student():p(*new Person()){} //这步不能少,一定得初始化
void show(){
p.show();
cout<<" "<<number<<endl;
}
private:
string number;
Person &p;
};
int main(){
Student s("zhang",22,"091150");
s.show();
system("pause");
return 0;
}
<SPAN style="BACKGROUND-COLOR: #ffffff; FONT-FAMILY: Arial"></SPAN> www.
特别注意包含指针和引用指针,要new一个,最好加多一个析构函数delete删除一个,包含引用的时候,别忘了初始化。