派生类(参数多于基类)是否可以使用基类函数和重载运算符C++?



我是c++类的新手,所以这个问题对一些人来说可能看起来很愚蠢,但我想知道我们是否可以在派生类中使用基类函数,就像我们使用构造函数一样?

据我所知,基类中的构造函数可以在派生类中使用,而无需一次又一次地复制相同的代码行,只需稍微修改构造函数以适应派生类的附加参数。例如:

class parent{
protected:
char *p;
public:
parent()
{
p=NULL;
}
parent(char ch[10])
{
/// initialization for p with ch (p=ch);
}
/// other functions and destructor ..
};
class child: public parent{
protected:
char *c;
public:
child():parent()
{
c=NULL;
}
child(char ch1[10], char ch2[10]): parent(ch1)
{
/// initialization for c with ch2 (c=ch2);
}
};

我试着用构造函数、父类函数和重载运算符做一些类似的事情,但没有成功(也许我做错了什么(:

class parent{

protected:

char *p;

public:

parent()
{
p=NULL;
}

parent(char ch[10])
{
/// initialization for p with ch (p=ch);
}
parent &operator=(const parent &p1)
{
/// overloading the operator for parent class parameters;
}

/// other functions and destructor ..
};

class child: public parent{

protected:
char *c;

public:
child():parent()
{
c=NULL;
}
child(char ch1[10], char ch2[10]): parent(ch1)
{
/// initialization for c with ch2 (c=ch2);
}
child &operator=(const parent &p1, const child &p2): parent &operator=(p1)
{ 
////didn't work
}
};

这就是我问这个问题的原因。

我主要想知道这是否可能,因为这对运算符重载很有帮助(通常我需要复制粘贴重载运算符的代码,从基类到派生类,然后再添加几行,这取决于派生类中有多少参数。但一次又一次地写或复制粘贴同一行代码是很烦人的(。

那么有解决方案吗?

两个问题。

赋值运算符总是必须只接受一个参数。如果你仔细想想,两个论点是没有意义的,因为=符号的右手边总是只有一件事:

child1 = child2; // child2 is passed into operator= for child1

由于const parent&特别是const child&,所以这个问题很容易解决:取一个类型为const child&的参数,并将其用作要初始化的parentchild

第二个问题是使用仅适用于构造函数的特殊冒号语法。如果要调用父级的赋值运算符,则需要使用不同的语法。

child &operator=(const child &p)
{
parent::operator=(p);
c = p.c;
}

通常,要调用基类成员,需要给出特定的基类名称(因为一个类可以有多个基类,所有基类都可能定义同一个成员函数(,然后是两个冒号::,然后是函数名。

(顺便说一句,将数组作为参数,然后在类中存储原始指针可能是个坏主意,因为数组将超出范围,指针将不再引用任何内容。最好使用std::string进行存储。(

最新更新