c++ - 继承构造函数

标签 c++ class inheritance constructor

我有一个名为 myGraph 的类,它派生自 graph

如果我在调用构造函数时知道顶点数,我将能够使用下面的构造函数。

myGraph(int numOfV) : graph(numOfV)
{
    // initialize...
}

我想计算构造函数中的顶点数,然后继承 graph inside 构造函数。怎么做?

myGraph(int a, int b)
{
    /* using a,b to initialize...  
       a sequence of push operation on (vector<T>)verticeList */

    int numOfV = this->verticeList.size();
    // inherit...
    myGraph(numOfV);  // it will not work


}

请注意

  1. 我用来计算顶点数的过程很复杂。(多行代码而不是a+b)

  2. 顶点个数取决于myGraph中的实例变量,所以我需要先初始化myGraph的成员,然后继承剩余的部分。

最佳答案

如果预初始化有很多逻辑,您可以在一个方法中将其分开:

struct myGraph
{
    myGraph(int a, int b) : graph(myGraph::computeNoVertices(a,b))
    {
    }
    static int computeNoVertices(int a, int b)
    {
        //whole chunk of code 
    }
};

关于c++ - 继承构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16953133/

相关文章:

c++ - 操作动态库加载的符号解析顺序

jquery - 如何使用 jQuery 动态地将 css 行高分配给嵌套对象?

java - 如何解决接口(interface)和继承之间的问题

python - 为什么定义类时括号是可选的,而定义函数时是必须的?

c# - 使用类或函数

c++ - 类异常和运算符

ruby - 形状继承示例和 "The Ruby way"

c++ - 重做安装程序(Linux)

C++ 设置 : storing duplicates: confused about < operator

c++ - ECS序列化