【发布时间】:2020-09-06 17:12:03
【问题描述】:
当我在learncpp.com上看到以下代码时,我正在研究对象组合...所有定义都在.h文件中,只是为了使代码简洁。
问题是:在初始化 Creature 对象时的 main.cpp 文件中,传递了正确的参数 {4,7}(我认为它调用了 Point2D 的构造函数)而不是对象...这是如何工作的,为什么?
另外,如果传递了 (4,7) 而不是 {4,7},我得到一个错误,因为参数不匹配...为什么?
提前谢谢。
Point2D.h:
#ifndef POINT2D_H
#define POINT2D_H
#include <iostream>
class Point2D
{
private:
int m_x;
int m_y;
public:
// A default constructor
Point2D()
: m_x{ 0 }, m_y{ 0 }
{
}
// A specific constructor
Point2D(int x, int y)
: m_x{ x }, m_y{ y }
{
}
// An overloaded output operator
friend std::ostream& operator<<(std::ostream& out, const Point2D &point)
{
out << '(' << point.m_x << ", " << point.m_y << ')';
return out;
}
// Access functions
void setPoint(int x, int y)
{
m_x = x;
m_y = y;
}
};
#endif
生物.h:
#ifndef CREATURE_H
#define CREATURE_H
#include <iostream>
#include <string>
#include "Point2D.h"
class Creature
{
private:
std::string m_name;
Point2D m_location;
public:
Creature(const std::string &name, const Point2D &location)
: m_name{ name }, m_location{ location }
{
}
friend std::ostream& operator<<(std::ostream& out, const Creature &creature)
{
out << creature.m_name << " is at " << creature.m_location;
return out;
}
void moveTo(int x, int y)
{
m_location.setPoint(x, y);
}
};
#endif
Main.cpp:
#include <string>
#include <iostream>
#include "Creature.h"
#include "Point2D.h"
int main()
{
std::cout << "Enter a name for your creature: ";
std::string name;
std::cin >> name;
Creature creature{ name, { 4, 7 };
// Above {4,7} is passed instead of an object
while (true)
{
// print the creature's name and location
std::cout << creature << '\n';
std::cout << "Enter new X location for creature (-1 to quit): ";
int x{ 0 };
std::cin >> x;
if (x == -1)
break;
std::cout << "Enter new Y location for creature (-1 to quit): ";
int y{ 0 };
std::cin >> y;
if (y == -1)
break;
creature.moveTo(x, y);
}
return 0;
}```
【问题讨论】:
-
在这种情况下,
(4,7)是带括号的comma operator,结果为7。在上下文中,大括号{ 4, 7 }表示Point2D类型的对象。 -
Creature creature{ name, { 4, 7 };此代码无法编译,您的大括号不匹配。
标签: c++ object parameters constructor