【发布时间】:2022-01-25 00:40:00
【问题描述】:
为什么在下面的代码中设置c1 = 10 会破坏对象的所有其他变量值(a、b、c)。该语句应该调用构造函数,并且在定义构造函数时,它将a 的值设置为10,但是当我尝试访问b 和c 的值时;它给了我垃圾值。
#include<iostream>
using namespace std;
class abc{
private:
// properties
int a,b, c;
public:
void setdata(int x,int y)
{
a = x;
b = y;
}
void showdata(){
cout << "a = " << a << " b = " << b << "\n";
}
// constructors
abc(){}
abc(int k)
{
a=k;
}
};
int main()
{
abc c1; // object intialization
c1.setdata(6,7); // setting values of properties
c1.showdata(); // printing values
c1 = 10; // primitive to class type conversion, constructor is being called
c1.showdata(); // why value of b and other variables is getting changed ?
return 0;
}
【问题讨论】:
-
您在
c1 = 10;行中创建了一个新对象(通过隐式转换构造函数)——显然,新对象对任何先前对象的值一无所知
标签: c++ c++11 constructor