如何在c++中定义以struct为数据成员的类中的构造函数
How to define constructor in class with struct as data member in c++?
我在类中创建了一个结构作为数据成员。现在,我想创建一个构造函数,将我的数据成员传递给它。如何在构造函数中传递结构。
我写了这个代码,但它不起作用。
#include <iostream>
#include <cmath>
using namespace std;
class circle
{
private:
struct center
{
int xcord;
int ycord;
};
struct center cordinate;
float radius;
public:
circle()
{
cordinate.xcord=0;
cordinate.ycord=0;
radius=0;
};
circle(int x, int y, float r) : cordinate.xcord(x), cordinate.ycord(y), radius(r)
{};
void showdata()
{
cout<<"Center(x,y) = ("<<cordinate.xcord<<","<<cordinate.ycord<<")"<<endl;
cout<<"Radius = "<<radius<<endl;
}
};
int main()
{
circle c1;
c1.showdata();
}
或者,如果我这样写,它仍然不起作用。
circle(int x, int y, float r) : center.xcord(x), center.ycord(y), radius(r)
{};
或
circle(int x, int y, float r) : center.cordinate.xcord(x), center.cordinate.ycord(y), radius(r)
{};
如何将结构传递给构造函数?
您可以初始化cordinate
成员,如下所示:
circle(int x, int y, float r) : cordinate{x, y}, radius{r} {}
此外,您的默认构造函数可以简化为:
circle() : circle(0, 0, 0) {}
其委托给3参数构造函数。更好的是,只需对所有字段使用类内成员初始值设定项:
struct center
{
int xcord = 0;
int ycord = 0;
} cordinate;
float radius = 0;
然后你可以默认默认构造函数:
circle() = default;
这是一个演示。
相关文章:
- 如何在c++中定义以struct为数据成员的类中的构造函数
- 在 C++ 中,默认情况下构造函数为类的数据成员提供的值是多少?
- 错误: 无效使用非静态数据成员"应用程序::应用程序构造函数"
- 在成员构造函数之后调用基类构造函数
- C++:如何在对象构造过程中调用初始值设定项列表之外的成员构造函数
- 用作成员构造函数参数的函数的求值顺序
- 从成员构造函数(Brace Initializer vs Initializer列表)抛出异常
- 不正确的成员构造函数定义
- 作为其他类成员的类:创建一个接受所有数据的构造函数
- 将数据从构造函数传输回调用方法时更改数据成员
- 我可以基于模板参数将某个值传递给成员构造函数吗
- 在类定义中调用成员构造函数
- 使用已删除的副本构造函数和初始值设定项列表重载调用类定义中的成员构造函数
- 正在从成员构造函数调用虚拟函数
- c++初始化类成员构造函数
- c++模板限制成员构造函数
- 使用静态数据的构造函数在main()之前执行工作
- Valgrind显示的数据在构造函数c++中肯定丢失了
- 访问私有数据的构造函数
- c++中使用相同数据成员和函数的两个类之间的继承