类与类之间的关系

#include<iostream>
using namespace std;
class A
{
public:
void func() {
cout << "funcA" << endl;
}
int a;
};
//类B拥有类A 的成员变量,B has A,即类B依赖于类A
class B
{
public:
void funcB()
{
}
A a;
};
//耦合度:高内聚 低耦合 ,程序员追求的最高境界设计模式
//类C的成员 需要类A的形参, 类C use A ,耦合度低一些
class C
{
public:
void funcC(A *a)
{
}
};
//类D继承A,即类D is A,耦合度高
class D :public A
{
public:
void funcD()
{
cout << a << endl;//直接打印继承过来的a
}
};
int main()
{
cout << "" << endl;
return 0;
}
继承的基本概念

#include<iostream>
#include<string> //string.h 是C语言的的字符串头文件
using namespace std;
class Student
{
public:
Student(int id,string name)
{
this->id = id;
this->name = name;
}
void printS()
{
cout << "id = " << this->id << ", name = " << this->name << endl;
}
private:
int id;
string name;
};
//创建一个新的学生类,增加score功能
class Student2
{
public:
Student2(int id,string name,int score)
{
this->id = id;
this->name = name;
this->score = score;
}
void printS()
{
cout << "id = " << this->id << ", name = " << this->name << endl;
cout << "score = " << this->score << endl;
}
private:
int id;
string name;
int score;//新add
};
//通过继承创建一个新的学生类
class Student3 :public Student
{
public:
Student3(int id,string name,int score) :Student(id,name)//通过父类来初始化
{//在使用子类构造是,编译器会默认调用父类构造(不写就默认调用无参的父类构造)
this->score = score;
}
void printS()
{
Student::printS();
cout << "score = " << this->score << endl;
}
private:
int score;
};
int main()
{
Student3 s3(1,"fyy",100);
s3.printS();
return 0;
}
总结:
耦合度:高内聚 低耦合 ,程序员追求的最高境界设计模式
在使用子类构造是,编译器会默认调用父类构造(不写就默认调用无参的父类构造)
49

被折叠的 条评论
为什么被折叠?



