簡體   English   中英

Object 作為參數傳遞,就像我們傳遞構造函數值一樣

[英]Object passed as parameters as if we are passing constructor values

當我在 learncpp.com 上遇到以下代碼時,我正在研究 Object 組合...所有定義都在.h 文件中,只是為了使代碼簡潔。

問題是:在 main.cpp 文件中,當初始化 Creature object 時,傳遞了正確的參數 {4,7}(我認為它調用了 Point2D 的構造函數)而不是 object...這是如何工作的,為什么?

此外,如果傳遞了 (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

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

這是 復制列表初始化(C++11 起)。

給定Creature creature{ name, { 4, 7 } }; ,作為效果,由構造函數Point2D::Point2D(int, int)從支撐初始化列表{ 4, 7 }構造一個臨時Point2D 然后將臨時值傳遞給Creature的構造函數。

正如@Someprogrammerdude 的評論所解釋的, (4,7)不能以這種方式工作。 這是一個逗號運算符表達式,它只返回第二個操作數。 您可以像Creature creature{ name, Point2D( 4, 7 ) }; .

當你調用這個時:

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

{4, 7}部分被確定為Point2D類型,並使用復制列表初始化構造。 當您使用(4, 7)時,這是用括號括起來的逗號運算符。 它導致值7並且不能用於初始化Point2D

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM