相关疑难解决方法(0)

15
推荐指数
1
解决办法
417
查看次数

临时函数调用的构造被解释为声明

最近我遇到了一个问题,不知何故(但只是某种程度上)对我有意义.它基于解释临时的构造作为单个(!)构造函数参数的声明.请看下面的最小例子.

#include <iostream>

class Foo0{
public:
  Foo0(int a){};
  void doStuff() {std::cout<<"maap"<<std::endl;};
};

class Foo1{
public:
  Foo1(int a){};
  void doStuff() {std::cout<<"maap"<<std::endl;};
};

class Foo2{
public:
  Foo2(int a){};
  void doStuff() {std::cout<<"maap"<<std::endl;};
};

class Bar{
public:
  Bar(Foo0 foo0, Foo1 foo1, Foo2 foo2){};
};

int main () {
  int x = 1;

  Bar bar0(Foo0(x), Foo1(x), Foo2(x)); // Does not work: conflicting declaration ‘Foo1 x’ previous declaration as ‘Foo0 x’; conflicting declaration ‘Foo2 x’ previous declaration as ‘Foo0 x’
  Bar bar1(Foo0{x}, Foo1(x), Foo2(x)); // Works …
Run Code Online (Sandbox Code Playgroud)

c++ construction temporary most-vexing-parse

8
推荐指数
1
解决办法
523
查看次数

代码用clang编译但不用gcc编译

我有这段代码可以用clang(甚至是-Weverything)编译好,但gcc会发出错误.

#include <iostream>
#include <vector>
#include <fstream>

using namespace std;

class PhonebookWriter
{
public:

  PhonebookWriter(const string& fname):
    fname_(fname), names_(), numbers_() {}

  PhonebookWriter& operator()(const string& name,
                  const string& number)
  {
    names_.push_back(name);
    numbers_.push_back(number);
    return *this;
  }

  ~PhonebookWriter(void)
  {
    ofstream f(fname_.c_str());
    for(size_t i=0;i<names_.size();++i)
      f << names_[i] << " " << numbers_[i] << "\n";
    f.close();
  }

private:
  const string fname_;
  vector<string> names_;
  vector<string> numbers_;
};

namespace {
  void write_guests_data(const string& fname)
  {
    PhonebookWriter(fname)("Mr Foo Bar","12345")("Mrs Bar Foo","54321");
  }
}

int main(void)
{
  write_guests_data("phone_book.txt");

  return …
Run Code Online (Sandbox Code Playgroud)

c++ gcc clang

4
推荐指数
1
解决办法
204
查看次数