C++ 结构实例
我已经研究这个问题两天了,但是运气不好 我预定义了以下结构C++ 结构实例,c++,data-structures,constructor,instance,C++,Data Structures,Constructor,Instance,我已经研究这个问题两天了,但是运气不好 我预定义了以下结构 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::Mot
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(..);
我知道我把类、结构、构造函数和析构函数搞砸了;问题是我找不到一个合适的教程,如果你能为我链接一个,我将不胜荣幸
提前感谢:-)没错;你应该做的是:
Motor M(123);
(其中123是一个端口)
当你只说电机M时代码>,编译器尝试通过调用无参数构造函数来构造此对象。你没有任何定义。但是,您可以像上面所示那样传递所需的参数
当然,另一种解决方案是只添加一个无参数构造函数,但这需要您的基类Port
也有一个构造函数,或者您传递一个固定值:
Motor() : Port(123) {} // fixed value
Motor() {} // assumes Port has a parameterless constructor
对,;你应该做的是:
Motor M(123);
(其中123是一个端口)
当你只说电机M时代码>,编译器尝试通过调用无参数构造函数来构造此对象。你没有任何定义。但是,您可以像上面所示那样传递所需的参数
当然,另一种解决方案是只添加一个无参数构造函数,但这需要您的基类Port
也有一个构造函数,或者您传递一个固定值:
Motor() : Port(123) {} // fixed value
Motor() {} // assumes Port has a parameterless constructor
Motor
有一个接受一个参数的构造函数,port\u t
,因此不会生成默认构造函数(一个没有参数的构造函数)。尝试:
如果端口有合理的默认值
,您可以向电机添加默认构造函数
:
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); }
....
};
Motor
有一个接受一个参数的构造函数,port\u t
,因此不会生成默认构造函数(一个没有参数的构造函数)。尝试:
如果端口有合理的默认值
,您可以向电机添加默认构造函数
:
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); }
....
};
我很惊讶有一个教程没有提到这一点。 C++中没有任何结构。关键字
struct
定义了
类类型,与关键字class
完全相同。唯一的区别是
1) 当您使用关键字struct
时,您开始使用public
;什么时候
你使用关键字类
,你开始私有
;二是继承
默认情况下,对于struct
,是public
,对于class
,是private
。因此:
struct Motor : Port
{
Motor( port_t port ) : Port( port ) {}
// ...
};
与以下内容完全相同:
class Motor : public Port
{
public:
Motor( port_t port ) : Port( port ) {}
// ...
};
由于您提供了构造函数,编译器不会生成
默认构造函数。我很惊讶有一个教程没有提到这一点。 C++中没有任何结构。关键字
struct
定义了
类类型,与关键字class
完全相同。唯一的区别是
1) 当您使用关键字struct
时,您开始使用public
;什么时候
你使用关键字类
,你开始私有
;二是继承
默认情况下,对于struct
,是public
,对于class
,是private
。因此:
struct Motor : Port
{
Motor( port_t port ) : Port( port ) {}
// ...
};
与以下内容完全相同:
class Motor : public Port
{
public:
Motor( port_t port ) : Port( port ) {}
// ...
};
由于您提供了构造函数,编译器不会生成
默认构造函数