gpt4 book ai didi

c++ - 对象作为参数传递,就像传递构造函数值一样

转载 作者:行者123 更新时间:2023-12-03 12:51:58 24 4
gpt4 key购买 nike

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

问题是:在 main.cpp 文件中,当初始化 Creature 对象时,会传递右参数 {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;
}```

最佳答案

当您调用此方法时:

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

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

关于c++ - 对象作为参数传递,就像传递构造函数值一样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61911356/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com