【发布时间】:2019-10-23 22:17:06
【问题描述】:
我是第一次在 C++ 中做 OOP。我注意到它与我过去做过 OOP 的其他语言非常不同。
到目前为止一切都很好,但是我遇到了一个问题,我需要一个构造函数来接收我创建的作为参数的对象,并且由于某些原因它拒绝编译并抛出错误。
我在网上对这个问题进行了深入研究,但我没有看到与我的情况足够相似的案例,而且答案也有很大差异。我想要解决这个问题的正确方法,所以我可以在整个项目中遵循这些约定。
这是引发错误的头文件(Player.h):
#pragma once
// Header files
#include "Square.h"
class Player
{
private:
// Private variables
Square _position;
public:
// Public constructors declarations
Player(Square position);
// Public functions declaration
void setPosition(Square position);
Square getPosition();
};
这是引发错误的 CPP 文件 (Player.cpp):
// Header files
#include "Player.h"
// Public constructors
Player::Player(Square position) // <---------- ERROR LOCATION
{
_position = position;
}
// Public functions
void Player::setPosition(Square position)
{
_position = position;
}
Square Player::getPosition()
{
return _position;
}
以防万一,这里是参数对象的头文件(Square.h):
#pragma once
class Square
{
private:
// Private variables
int _x;
int _y;
public:
// Public constructors declarations
Square(int x, int y);
// Public functions declaration
void setX(int x);
int getX();
void setY(int y);
int getY();
};
这里也是参数对象的CPP文件(Square.cpp):
// Header files
#include "Square.h"
// Public constructors
Square::Square(int x, int y)
{
_x = x;
_y = y;
}
// Public functions
void Square::setX(int x)
{
_x = x;
}
int Square::getX()
{
return _x;
}
void Square::setY(int y)
{
_y = y;
}
int Square::getY()
{
return _y;
}
以下是编译器抛出的错误:
在文件“Player.cpp”的第 4 行:
错误 E0291:类“Square”不存在默认构造函数
错误 C2512: 'Square' : 没有合适的默认构造函数可用
【问题讨论】:
-
旁注:
Player::Player(Square position)将复制Square。这不是很多工作,因为它是一对ints,但是对于较大的对象需要注意。您可能希望Player::Player(const Square &position)通过引用传递以节省复制。它被标记为 const 是因为它扩大了您可以传递的内容,并使所有内容都为 const 直到被证明否则有助于防止某些类型的错误潜入。 -
您可能想观看这个关于现代 C++ 中 OOP 的 cppcon 演讲。特别是使用 override 来标记您的方法可以在您意外重载时避免很多悲伤。 youtube.com/watch?v=32tDTD9UJCE