Atu*_*tul 3 c++ constructor class
#include <iostream>
using namespace std;
class date{
public:
int month;
int day;
int year;
private:
date(int x, int y, int z);
public:
date(int x, int y);
};
date::date(int x, int y, int z): month{x}, day{y}, year{z} {
cout << "Hello you called me PRIVATE constructor" << endl;
}
date::date(int x, int y){
cout << "Hello you called me PUBLIC constructor" << endl;
date(x, y, 100);
}
int main(){
date x{11, 21};
cout << x.month << endl;
cout << x.day << endl;
cout << x.year << endl;
}
Run Code Online (Sandbox Code Playgroud)
正如你在上面的代码中看到的,我有两个构造函数,在main中我用两个参数创建对象x.
这应该调用公共构造函数,后者又调用私有构造函数并初始化公共成员月份日和年份.
但是当我打印出会员价值时,我没有得到理想的结果.
Hello you called me PUBLIC constructor
Hello you called me PRIVATE constructor
392622664
1
0
Run Code Online (Sandbox Code Playgroud)
而输出应该是:
Hello you called me PUBLIC constructor
Hello you called me PRIVATE constructor
11
21
100
Run Code Online (Sandbox Code Playgroud)
我不知道我做错了什么.任何帮助将不胜感激.谢谢.
构造函数没有名称,也无法调用.该表达式date(x, y, 100);使用私有构造函数创建一个临时实例,该构造函数会立即销毁.您可以委派构造,但需要使用正确的构造函数委派语法.要委托构造函数,必须在初始化列表中执行此操作.它必须是初始化列表中的唯一元素.例如 :
#include <iostream>
using namespace std;
class date {
public:
int month;
int day;
int year;
private:
date(int x, int y, int z);
public:
date(int x, int y);
};
date::date(int x, int y, int z) : month{ x }, day{ y }, year{ z } {
cout << "Hello you called me PRIVATE constructor" << endl;
}
date::date(int x, int y) : date(x, y, 100) {
cout << "Hello you called me PUBLIC constructor" << endl;
}
int main() {
date x{ 11, 21 };
cout << x.month << endl;
cout << x.day << endl;
cout << x.year << endl;
}
Run Code Online (Sandbox Code Playgroud)