标题:c++设计与编程之包含关系(包容关系)
只看楼主
shitainong
Rank: 1
等 级:新手上路
帖 子:70
专家分:0
注 册:2012-7-6
结帖率:0
 问题点数:0 回复次数:1 
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删除一个,包含引用的时候,别忘了初始化。
搜索更多相关主题的帖子: 关系 include public 
2012-07-25 17:14
pangding
Rank: 19Rank: 19Rank: 19Rank: 19Rank: 19Rank: 19
来 自:北京
等 级:贵宾
威 望:94
帖 子:6784
专家分:16751
注 册:2008-12-20
得分:0 
根据帖子的标题很难猜出帖子的内容是什么主题。
2012-07-26 00:42



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-374099-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.097040 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved