对象作为参数传递,就好像我们正在传递构造函数值一样

Object passed as parameters as if we are passing constructor values

本文关键字:构造函数 一样 参数传递 我们 对象      更新时间:2023-10-16

当我在 learncpp.com 上遇到以下代码时,我正在研究对象合成......所有定义都在 .h 文件中,只是为了使代码简洁。

问题是:在 main.cpp 文件中,当 Creature 对象初始化时,传递右参数 {4,7}(我认为它调用了 Point2D 的构造函数(而不是对象......这是如何工作的,为什么?

此外,如果传递 (4,7( 而不是 {4,7},我会收到一个错误,因为参数不匹配......为什么?

提前感谢。

点2D.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

主.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;
}```

当你调用这个时:

Creature creature{ name, { 4, 7 }}; 

{4, 7}部件被确定为类型Point2D并使用复制列表初始化构造。当您使用(4, 7)时,这是括在括号中的逗号运算符。它会导致值7,并且不能用于初始化Point2D

这是复制列表初始化(自C++11以来(。

给定Creature creature{ name, { 4, 7 } };,作为效果,临时Point2D由构造函数Point2D::Point2D(int, int)从大括号初始化列表{ 4, 7 }构造。然后将临时传递给Creature的构造函数。

正如@Someprogrammerdude的评论所解释的那样,(4,7)不是这样工作的。这是一个逗号运算符表达式,只返回第二个操作数。您可以显式指定临时,如Creature creature{ name, Point2D( 4, 7 ) };