【问题标题】:Instance of a structure结构实例
【发布时间】:2012-03-23 10:16:14
【问题描述】:

我已经研究这个问题 2 天了,但没有运气。

我预定义了以下结构

struct Motor : Port {
Motor(port_t port) : Port(port) {}
void moveAtVelocity(int velocity) { move_at_velocity(m_port, velocity); }
....
};

然后我尝试调用结构的实例

Motor M;

我得到了

Error: No matching function for call to Motor::Motor()
Note: Candidates are Motor::Motor(port_t)

如何调用实例,例如我可以使用以下方法

moveAtVelocity(..);

我知道我在类和结构以及构造函数和析构函数之间搞砸了;问题是我找不到合适的教程,如果你可以为我链接一个,额外的荣誉。

提前致谢:-)

【问题讨论】:

    标签: c++ data-structures constructor instance


    【解决方案1】:

    没错;你应该拥有的是:

    Motor M(123);
    

    (其中 123 是一个端口)。

    当您只是说Motor M; 时,编译器会尝试通过调用无参数构造函数来构造此对象。你没有任何定义。但是,您可以像上面显示的那样传递所需的参数。

    当然,另一种解决方案是只添加一个无参数的构造函数,但这需要您的基类 Port 也有一个,或者让您传递一个固定值:

    Motor() : Port(123) {}  // fixed value
    Motor() {} // assumes Port has a parameterless constructor
    

    【讨论】:

      【解决方案2】:

      Motor 有一个构造函数,它接受一个参数port_t,因此不会生成默认构造函数(一个没有参数的构造函数)。试试:

      Motor M(14); // where 14 is a guess by me at what a `port_t` is.
      

      如果port_t 有合理的默认值,您可以将默认构造函数添加到Motor

      struct Motor : Port {
          Motor() : Port(14) {}
          Motor(port_t port) : Port(port) {}
          void moveAtVelocity(int velocity) { move_at_velocity(m_port, velocity); }
          ....
      };
      

      或者在当前构造函数中为参数指定一个默认值:

      struct Motor : Port {
          Motor(port_t port = 14) : Port(port) {}
          void moveAtVelocity(int velocity) { move_at_velocity(m_port, velocity); }
          ....
      };
      

      【讨论】:

        【解决方案3】:

        我很惊讶可能有一个教程没有提到这一点。 C++ 中实际上没有任何结构。关键字struct 定义了一个 类类型,与关键字class 完全一样。唯一的区别是 1)当您使用关键字struct时,您开始使用public;什么时候 你使用关键字class,你开始private;和 2) 继承 默认为publicstructprivateclass。所以:

        struct Motor : Port
        {
            Motor( port_t port ) : Port( port ) {}
            //  ...
        };
        

        完全一样:

        class Motor : public Port
        {
        public:
            Motor( port_t port ) : Port( port ) {}
            //  ...
        };
        

        而且由于您提供了构造函数,编译器不会生成 默认构造函数。

        【讨论】:

          猜你喜欢
          • 2016-03-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-05-08
          • 2019-12-27
          • 2018-07-10
          相关资源
          最近更新 更多