构造函数c ++中的奇怪函数调用

时间:2014-10-26 13:36:33

标签: c++ constructor

我正在编写一个enigma机器,并且在为我的机器类制作构造函数时遇到问题。尽管必须在构造函数的参数中提供一个插板,但似乎正在调用一个插件板的构造函数。这是错误

Machine.cpp: In constructor ‘Machine::Machine(std::list<Rotor>, Plugboard)’:
Machine.cpp:6:48: error: no matching function for call to ‘Plugboard::Plugboard()’
 Machine::Machine(list<Rotor> rots, Plugboard pb) {

Machine.cpp:

#include "Machine.h"

using namespace std;


Machine::Machine(list<Rotor> rots, Plugboard pb) {

  plugboard = pb;
  rotors = rots;

}

//give c's alphabet index
int Machine::getPosition(char c) {
  if (c >= 'A' && c <= 'Z') {
    return c - 'A';
  }
  else  {
    cout <<  "not an accepted character";
    return -1;
  }
}

//give letter at index i in alphabet
char Machine::atPosition(int i) {
  assert(i>=0 && i<=25);
  return "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[i];
}

char Machine::encode(char c) {
  assert(c >= 'A' && c <= 'Z');
  //plugboard
  c = plugboard.getMatch(c);
  //forward pass through rotors
  c = rotors[0].process(c);
  //reflector
  c = Reflector::reflect(c);
  //backwards pass through rotors
  c = rotors[0].processInverse(c);
  return c;

}

Machine.h:

#ifndef MACHINE_H
#define MACHINE_H

#include <stdexcept>
#include <iostream>
#include <assert.h>
#include <list>
#include "Reflector.h"
#include "Rotor.h"
#include "Plugboard.h"

class Machine{

  public:

    Machine(std::list<Rotor> rots, Plugboard pb);   
    static int getPosition(char c);
    static char atPosition(int i);
    char encode(char c);

  private:

    std::list<Rotor> rotors;
    Plugboard plugboard;

};

#endif

1 个答案:

答案 0 :(得分:5)

那是因为在你的构造函数中,你首先默认构建plugboard,然后复制分配它。只需在初始化列表中构造它。并通过const &获取参数!

Machine(const std::list<Rotor>& rots, const Plugboard& pb)
: rotors(rots)
, plugboard(pb)
{ }