如何在C++中使用带参数的构造函数声明具有来自另一个类的类数据的对象
How to declare an object in C++ that has a Class Data from another class with constructor with parameters
我正在创建一个简单的对象。。。但是
我找不到一种"语义方式"来创建一个具有Class作为数据的带有构造函数的对象,所以我无法创建我的对象,即:
#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;
};
在您的情况下,您需要在Point
的构造函数中使用初始化列表,以便使用您定义的转换构造函数来构造Coordinate
:
class Point
{
public:
Point()
:
coordinate (42, 42) // you would somehow pass these to Point's constructor
{
}
};
原因是Coordinate
没有默认的构造函数(例如,可以在没有参数的情况下调用的构造函数)。通常,如果您没有定义默认构造函数,编译器会为您编写一个,但如果您定义任何其他构造函数,则不会发生这种情况。
您还可以通过指定默认参数将已经编写的convert构造函数修改为默认构造函数:
Coordinate(int axisX = 42, int axisY = 42) {
x = axisX;
y = axisY;
}
然而,我不确定这在你的程序中是否有意义。
您还可以实现Coordinate
:的默认构造函数
class Coordinate
{
public:
Coordinate ()
:
x (0) ,
y (0)
{
}
// ...
};
但是,您会遇到一个问题,您可能会使用x
和y
的有效但无意义的值实例化Coordinate
对象。
可能最好的方法是我建议的第一种方法,通过修改将坐标传递给Point
的构造函数:
class Point
{
public:
Point (int x, int y)
:
coordinate (x, y)
{
}
};
这将是这样构建的:
int main()
{
Point p(1,2);
}
现在不可能用无效或无意义的Coordinate
实例化Point
对象。
class Point
{
public:
point(int axisX,int axisY):Coordinate(axisX,axisY);
string color;
Coordinate coordinate;
};
相关文章:
- 在他自己的方法中,有可能将一个对象取消引用到另一个对象吗
- 为什么C++在将一个对象复制到另一个对象时需要对这两个对象进行低级常量限定
- 检查哪个对象调用了另一个对象的对象方法
- C++ 如何在将新对象分配给另一个对象时创建新对象
- 为什么我可以在不重载 "=" 运算符的情况下将一个对象分配给另一个对象?
- 如何在qt中将信号和插槽与另一个对象连接 --解决了
- 如何使用函数将一个对象的输入复制到另一个对象中
- 为什么我可以使用 memcpy 将一个对象变量复制到另一个对象变量
- 如何将包含另一个对象向量的对象保存到文件中,并使用C++中的二进制文件从文件中读回?
- 我重载了 << 和 = 运算符。为什么当我将一个对象分配给另一个对象并尝试打印它时,我会被打印出来?
- 打印对象的映射,其中另一个对象作为键
- 如何通过另一个对象中的命令正确地从一个对象返回数据
- 为什么将两个对象分配给另一个对象后,两个对象不一样?
- 复制赋值函数如何访问另一个对象的私有成员(Stroustroup 原则和实践书)?
- 为什么数组中对象的析构函数在被另一个对象替换时不被调用?
- C++将带有重载构造函数的对象添加到另一个对象
- 如何将指针从unique_ptr传递到另一个对象并管理寿命
- 如何将"this"的生命周期移动到C++中的另一个对象中?
- 2 个 COM 对象,并在另一个对象中使用其中一个对象的接口
- 将列表的对象C++移动到另一个对象