gpt4 book ai didi

c++ - 如何在 C++ 中声明一个对象,该对象具有来自另一个类的类数据以及带参数的构造函数

转载 作者:行者123 更新时间:2023-11-28 07:31:48 25 4
gpt4 key购买 nike

我正在创建一个简单的对象...但是

我找不到一种“语义方式”来创建一个对象,该对象具有一个类作为带有构造函数的数据,所以我无法创建我的对象,即:

#include <iostream>

using namespace std;

class Coordinate
{
public:
Coordinate(int axisX,int axisY) {
x= axisX;
y= axisY;
}
int x,y;
};

class Point
{
public:
string color;
Coordinate coordinate;
};

int main()
{

Point myPoint; //Error here also tried Point myPoint(1,1) or myPoint::Coordenate(1,1) etc...

return 0;
}

最佳答案

您必须为 Point 提供构造函数,以适本地初始化 coordinate 成员:

class Point
{
//make data members private!
string color;
Coordinate coordinate;
public:
Point()
: color("red") //initialize color
, coordinate(4,13) //initialize coordinate
{}

// and/or:
Point(int x, int y, std::string clr = "")
: color(clr)
, coordinate(x,y)
{}
};

您可能想查找构造函数初始化列表(冒号和左大括号之间的部分),因为它们对您来说可能是新的。您的 Coordinate 构造函数也可以从初始化列表中受益:

class Coordinate
{
public:
Coordinate(int axisX,int axisY)
: x(axisX), y(axisY)
{}

private:
//again, data members should be private in most cases
int x,y;
};

关于c++ - 如何在 C++ 中声明一个对象,该对象具有来自另一个类的类数据以及带参数的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17527966/

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