錯誤顯示:no matching functions for call to birthday::birthday()。我應該如何在另一個類中宣告一個類的物件?
#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;
}
uj5u.com熱心網友回復:
只需定義一個默認建構式birthday,這樣您就可以在不初始化的情況下創建一個型別的物件。
或者您可以默認初始化person型別私有資料成員day。
uj5u.com熱心網友回復:
雖然關于添加默認 c'tor 的答案在birthday技術上是正確的,但我認為他們錯過了真正的問題。鑒于您如何宣告變數b和pin main(),看起來您的意圖是將birthday變數b添加到person變數中,這意味著您真正想要的是修改person()建構式:
person(string x, birthday b): name(x), day(b)
{ }
這將確保在構造物件時birthday為給定物件定義物件。personperson
這并不是說為其中一個birthday或添加一個默認的 c'torperson是錯誤的。事實上,這可能是可取的。但就其本身而言,它可能不會產生預期的效果。
uj5u.com熱心網友回復:
問題是您的類有birthday一個用戶定義的建構式,因此編譯器不會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;需要類的默認建構式birthday,但由于沒有,因此該陳述句導致上述錯誤。
解決方案
為了解決這個問題,您可以為您的班級生日添加一個默認建構式,如下所示:
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;
}
我所做的一些更改包括:
- 為 class 添加了默認建構式
birthday。 - 用于資料成員和內部類的類內初始化程式。
dateyearmonthbirthday - 您的代碼還有另一個問題。最初
cout<<day.printdate(),您的程式中有一個宣告。但是由于printdate()有回傳型別void,所以該陳述句cout<<day.printdate()會給你錯誤。為了解決這個問題,我cout從這個宣告中洗掉了。
修改后的程式的輸出可以在這里看到。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/429039.html
上一篇:文本操縱器:字串位置移動
