我的问题很简单,但是我陷入了困境。如何从基类中选择所需的构造函数?

// node.h
#ifndef NODE_H
#define NODE_H

#include <vector>

// definition of an exception-class
class WrongBoundsException
{
};

class Node
{
    public:
        ...

        Node(double, double, std::vector<double>&) throw (WrongBoundsException);
        ...
};

#endif


// InternalNode.h
#ifndef INTERNALNODE_H
#define INTERNALNODE_H

#include <vector>
#include "Node.h"


class InternalNode : public Node
{
    public:
        // the position of the leftmost child (child left)
        int left_child;
        // the position of the parent
        int parent;

        InternalNode(double, double, std::vector<double>&, int parent, int left_child) throw (WrongBoundsException);

    private:
        int abcd;

};

#endif


// InternalNode.cpp

#include "InternalNode.h"

#define UNDEFINED_CHILD -1
#define ROOT -1


// Here is the problem
InternalNode::InternalNode(double a, double b, std::vector<double> &v, int par, int lc)
throw (WrongBoundsException)
: Node(a, b, v), parent(par), left_child(lc)
{
    std::cout << par << std::endl;
}

我得到:
$ g++ InternalNode.cpp

InternalNode.cpp:16:错误:“InternalNode::InternalNode(double,double,std::vector>&,int,int)的声明(WrongBoundsException)”引发了不同的异常
InternalNode.h:17:错误:来自先前的声明“InternalNode::InternalNode(double,double,std::vector>&,int,int)”

更新0:修复丢失:

更新1:修复抛出异常

最佳答案

此简化的代码可以正确编译,但是由于缺少基类的构造函数定义,因此不会链接:

#include <vector>

// definition of an exception-class
class WrongBoundsException {
};

class Node {
    public:
        Node(double, double, std::vector<double>&)
                throw (WrongBoundsException);
};

class InternalNode : public Node {
    public:
        // the position of the leftmost child (child left)
        int left_child;
        // the position of the parent
        int parent;

        InternalNode(double, double, std::vector<double>&,
                        int parent, int left_child)
                        throw (WrongBoundsException);
    private:
        int abcd;

};

// Note added exception specification
InternalNode::InternalNode(double a, double b,
                            std::vector<double> &v,
                    int par, int lc) throw (WrongBoundsException)
        : Node(a, b, v), parent(par), left_child(lc)
{
}

顺便说一句,为什么您觉得需要使用异常规范?在C++中,它们通常看起来有点浪费时间。

10-08 08:03