[英]How do I declare the objects related to one class in other?
错误显示: no matching functions for call to birthday::birthday()
。 我还应该如何在另一个 class 中声明一个 class 的对象?
#include <iostream>
using namespace std;
class birthday
{
public:
birthday(int d,int m,int y)
{
date=d;
month=m;
year=y;
}
void printdate()
{
cout<<date<<"/"<<month<<"/"<<year<<endl;
}
private:
int date;
int month;
int year;
};
class person
{
public:
person(string x)
{
name=x;
}
void printname()
{
cout<< "the birthday person is "<< name << " whose birthday is on "<< day.printdate();
}
private:
birthday day;
string name;
};
int main()
{
birthday b(10,11,2007);
person p("Jessica");
p.printname();
return 0;
}
只需定义一个默认构造函数,这样您就可以创建一个 object 类型的birthday
而无需对其进行初始化。
或者你可以默认初始化person
类型的私有数据成员day
。
虽然关于为birthday
添加默认 c'tor 的答案在技术上是正确的,但我认为他们错过了真正的问题。 鉴于您在main()
中声明变量b
和p
的方式,看起来您的意图是将birthday
变量b
添加到person
变量中,这意味着您真正想要的是将person()
构造函数修改为这样的:
person(string x, birthday b): name(x), day(b)
{ }
这将确保在构造person
时为给定person
object 定义birthday
object。
这并不是说为birthday
或person
添加默认 c'tor 是错误的; 事实上,这可能是可取的。 但就其本身而言,它可能不会产生预期的效果。
问题是您的 class birthday
有一个用户定义的构造函数,因此编译器不会为您的 class 合成默认构造函数birthday::birthday()
。
所以当你写的时候,
class person
{
//other members here
private:
birthday day; //this need the default constructor of birthday. But since class birthday has no default constructor this statement gives error
};
在上面的片段中,语句, birthday day;
需要 class birthday
的默认构造函数,但由于没有,因此该语句导致上述错误。
要解决这个问题,您可以为 class 生日添加默认构造函数,如下所示:
class birthday
{
public:
//add default constructor
birthday() = default;
birthday(int d,int m,int y)
{
date=d;
month=m;
year=y;
}
void printdate()
{
cout<<date<<"/"<<month<<"/"<<year<<endl;
}
private:
//using in class initializers give some default values to the data members according to your needs
int date = 0;
int month =0;
int year = 0;
};
class person
{
public:
person(string x)
{
name=x;
}
void printname()
{
cout<< "the birthday person is "<< name << " whose birthday is on ";
day.printdate();//moved this out of the cout because printdat() does not return anything
}
private:
birthday day;
string name;
};
int main()
{
birthday b(10,11,2007);
person p("Jessica");
p.printname();
return 0;
}
我所做的一些更改包括:
birthday
添加了默认构造函数。birthday
中对数据成员date
、 year
和month
使用类内初始化器。cout<<day.printdate()
。 但是由于printdate()
的返回类型为void
,所以语句cout<<day.printdate()
会给你错误。 为了解决这个问题,我从这个声明中删除了cout
。修改后的程序output可以在这里看到。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.