-1

在 c++11 中,构造函数可以转发到初始化列表中的另一个构造函数。

可以像这个问题一样在初始化列表中调用函数

在构造函数委托中调用函数也可以吗?

我试过这样的代码:

#include <iostream>
#include <string>
#include <yaml-cpp/yaml.h>

using namespace std;

YAML::Node ParseFromFile(const string& filepath) {
  YAML::Node yaml;
  try {
    return YAML::LoadFile(filepath);
  } catch(const YAML::BadFile& e) {
    cout << "error";
  }
}

class A {
 public:
  A(YAML::Node yaml) {
    cout  << "Got" << endl;
  }
  A(const string& filepath) : A(ParseFromFile(filepath)) {}
};


int main(int argc, char** argv) {
  A a(string(argv[1]));
  YAML::Node yaml = ParseFromFile(string(argv[1]));
  A b(yaml);
  return 0;
}

对于上面的代码,只需传递一个空文件给它,它只会在b的初始化过程中打印一个“Got”。

==================================================== ======================

用 argv[1] 替换 string(argv[1]) 使它工作,任何想法为什么?

4

1 回答 1

3

回答已编辑的问题


问题是 main 中的第一行它被视为函数声明而不是变量初始化,实际上您是否使用 clang 编译它会给您一个警告:

警告:括号作为函数声明已消除歧义

这是由于标准中第 6.8 节中定义的歧义解决(AKA Most vexing parse)(强调我的...):

在涉及表达式语句和声明的语法中存在歧义:将函数样式显式类型转换 (5.2.3) 作为其最左侧子表达式的表达式语句与第一个声明符以 (.在这些情况下,声明就是声明

考虑以下示例:

#include <iostream>
#include <string>
#include <exception>
using namespace std;

struct A{
    string a;
    A(string s) : a(s){ cout<< "Ctor" <<endl;}
    A(int i) : A(to_string(i)){ }
};

void foo (A (*a)(string*)){
    cout<<"yay"<<endl;
}

int main(int argc, char** argv) {
    A         a1(     string(argv[1]) ); // function A a1(std::string*) declaration not a variable 
/*  ^         ^       ^
    |         |       |
return type   name   arg type 
Same as foo
*/
    // foo(a1);//  <- compiles but fails only due to linkage         
    A  a2 = A(string(argv[1])); // works
    A  a3{string(argv[1])}; // works
    A  a4(string{argv[1]}); // works
    A         a5(     ( string(argv[1]) ) ); // works allso but confusing imho
/*                    ^                 ^
notice extra paren.   |                 |
*/  
    return 0;
}

回答原始问题 FWIW


为什么不试试呢?

除非您调用将使用仍未初始化的成员的函数,否则应该没有问题。

例如(演示):

#include <iostream>
#include <string>
using namespace std;

class A {
 public:
  A(string x) {
    cout  << "Got "  << x << endl;
  }
  A(int x) : A(std::to_string(x)) {}
};


int main() {
    A a(15);
    return 0;
}
于 2014-08-07T05:22:58.593 回答