【发布时间】:2016-04-09 19:40:59
【问题描述】:
在层次结构中,子构造函数如何在c++中设置祖父构造函数的成员。
祖父>父亲>儿子
【问题讨论】:
-
C++ 术语是基类(父类)和派生类(子类)。 Smalltalk 术语是超类(父亲)和子类(儿子)。
标签: c++ c++11 constructor hierarchy class-hierarchy
在层次结构中,子构造函数如何在c++中设置祖父构造函数的成员。
祖父>父亲>儿子
【问题讨论】:
标签: c++ c++11 constructor hierarchy class-hierarchy
它不能,至少不能用初始化语法。给定这样的类
class grandfather {
int x;
};
class father : public grandfather {
int y;
};
class son : public father {
int z;
son();
};
写作
son::son() : x(0), y(1), z(2) { }
无效。只有直接基类构造函数可用,基成员不可用。这是可能的:
son::son() : father(), z(2) {
x = 0;
y = 1;
}
但最好像这样给father和grandfather添加构造函数
grandfather::grandfather(int xx) :
x(xx) { }
father::father(int xx, int yy) :
grandfather(xx), y(yy) { }
然后像这样son
son::son() : father(0, 1), z(2) { }
【讨论】:
不能。那不是它的工作。每个“级别”可能只初始化它上面的“级别”。应该是这样的。
但是,当您使用虚拟继承时,这条规则就消失了,每个“级别”都直接负责为其他每个“级别”提供构造函数参数。
【讨论】:
您使用成员初始化器列表将参数传递给直接基类构造函数。
喜欢
class Derived
: public Base
{
public:
Derived()
: Base( "joo hoo" ) // ← A member initializer list
{}
};
基类构造函数将依次将参数传递给其基类的构造函数,依此类推。
只有在虚拟继承的情况下,派生的派生的派生的...类可以直接初始化“祖父”类。这是一个高级话题,不太可能是你现在要问的。如果您遇到该问题,我建议您提出一个新问题。
关于术语:
C++ 术语是基类(父)和派生类(子)。
Smalltalk 术语是超类(父)和子类(子)。
father 和 son 这两个词一般不用(这是我第一次看到它们!),但有时会使用 parent 和child 表示层次结构中的位置——节点、类等等。
相关,虽然没有在这个问题中使用,但 C++ 中的 纯虚 函数对应于 Smalltalk 中的 子类责任 的方法。
【讨论】:
#include<iostream>
#include<string>
using namespace std;
class Person{
int age;
protected :
string name;
public:
Person(int a,string s)
{
age=a;
name=s;
}
Display_0()
{
cout<<"\nName : "<<name;
cout<<"\nAge : "<<age;
}
};
class Employe {
int employeid;
protected :
double salary;
public:
Employe(int id,double sal)
{
employeid=id;
salary=sal;
}
Display_1()
{
cout<<"Id is : "<<employeid;
cout<<"\nSalary is : "<<salary;
}
};
class Manager : public Person, public Employe
{
string type;
public:
Manager(string t,int id,double sal,int age,string name) : Employe( id, sal) , Person( age, name)
{
type=t;
}
string get_type()
{
return type;
}
Display_2()
{
Display_0();
cout << "\n";
Display_1();
cout<<"\nType is : "<<type;
}
};
class It_Manager : public Manager{
private :
int noOfPersons;
public:
It_Manager(int n,string na,int id,double sal,int age,string name) : Manager( na, id, sal, age, name)
{
noOfPersons=n;
}
Display_last()
{
Display_2();
cout<<"\nNo of Persons : "<<noOfPersons;
}
};
main()
{
It_Manager b(1,"Computer Scientist",152118,150000,100,"Muhammad Owais") ;
b.Display_last() ;
}
这里 It_Manager 是儿子 经理是父亲 和 Person 和 Employe 是祖父
在此帮助下,您可以获得基本概念和关于打印数据的信息,这取决于您的操作方式。可以使用成员函数来打印它。
【讨论】: