在C ++中调用超级构造函数之前要做一些事情

时间:2018-09-22 20:55:08

标签: c++ inheritance constructor

我可以在c ++中调用基类之前执行一些表达式吗?特别是,为基本构造函数准备输入/参数。例如:

class Figure {
    Point* vertex;
    Figure(Point vertex[MAX]) {
        this->vertex = vertex;
    }
};

class Triangle: public Figure {
    Triangle(Point p1, Point p2, Point p3) {
      //here it is my question, it is possible?
      Point pts[3] = {p1,p2,p3}; //preparing input for constructor
      Figure(pts); or Figure::Figure(pts); // calling the constructor 
    }
}; 

我不确定这个问题是否专门针对C ++,也许这是一个普遍的问题。谢谢!

1 个答案:

答案 0 :(得分:0)

如果您愿意稍微更改界面并使用c ++ 11或更高版本,则可以使用delegating constructorlist initialization进行此类操作。

library(dbplyr, warn.conflicts = FALSE)
library(dplyr, warn.conflicts = FALSE)
library(purrr, warn.conflicts = FALSE)
library(DBI, warn.conflicts = FALSE)
library(rlang, warn.conflicts = FALSE)

con <- DBI::dbConnect(RSQLite::SQLite(), path = ":dbname:")

db_mtcars <- copy_to(con, mtcars)

cyls <- c(4, 6, 8)

all <- cyls %>%
  map(~{
    db_mtcars %>%
      filter(cyl == .x) %>%
      summarise(mpg = mean(mpg, na.rm = TRUE)
      )
  }) %>%
  reduce(function(x, y) union(x, y)) 

all
#> # Source:   lazy query [?? x 1]
#> # Database: sqlite 3.22.0 []
#>     mpg
#>   <dbl>
#> 1  15.1
#> 2  19.7
#> 3  26.7

show_query(all)
#> <SQL>
#> SELECT AVG(`mpg`) AS `mpg`
#> FROM (SELECT *
#> FROM (SELECT *
#> FROM `mtcars`)
#> WHERE (`cyl` = 4.0))
#> UNION
#> SELECT AVG(`mpg`) AS `mpg`
#> FROM (SELECT *
#> FROM (SELECT *
#> FROM `mtcars`)
#> WHERE (`cyl` = 6.0))
#> UNION
#> SELECT AVG(`mpg`) AS `mpg`
#> FROM (SELECT *
#> FROM (SELECT *
#> FROM `mtcars`)
#> WHERE (`cyl` = 8.0))

dbDisconnect(con)