对象作为参数传递,就好像我们正在传递构造函数值一样
Object passed as parameters as if we are passing constructor values
当我在 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 ) };
。
相关文章:
- "error: no matching function for call to"构造函数错误
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 选择要调用的构造函数
- 如何委托派生类使用其父构造函数?
- 构造函数正在调用一个使用当前类类型的函数
- 没有用于初始化C++中的变量模板的匹配构造函数
- 初始化具有非默认构造函数的std::数组项的更好方法
- 当从函数参数中的临时值调用复制构造函数时
- 在c++构造函数中使用随机字符串生成器
- 一对向量构造函数:初始值设定项列表与显式构造
- 从构造函数抛出异常时如何克服内存泄漏
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 如何像函数一样调用构造函数
- Java是否有默认的复制构造函数(就像C++中一样)
- 像调用普通方法一样调用构造函数和析构函数的注意事项和风险
- 是struct的默认构造函数,就像c++中的类一样
- 我能让赋值运算符像复制构造函数一样工作吗