我已经编写了一个类型转换程序(Primitive到class类型).当我在DEV上运行这个时,它显示了垃圾值


#include < iostream > 
#include < iomanip >
using namespace::std;
#include < string.h >
class Human {
char Name[20];
int Age;
float Weight;
public:
Human() {
strcpy(Name, " ");
Age = Weight = 0;
}
Human(int AGE) {
this - > Age = Age;
}
Human(float Weight) {
this - > Weight = Weight;
}
Human(char * s) {
strcpy(this - > Name, s);
}
void GetData() {
cout << endl << "Enter the name   : ";
gets(Name);
cout << endl << "Enter the Age    : ";
cin >> Age;
cout << endl << "Enter the Weight :";
cin >> Weight;
}
void Display() {
cout << endl << "Name   :" << Name;
cout << endl << "Age    :" << Age;
cout << endl << fixed << "Weight :" << Weight << " Kg";
}
};
int main() {
Human h1;
h1 = 23; //It will assign 23 in Age
h1 = 67.45 f; //It will assign 67.45 in Weight
h1 = "Jimmy Neutron";
h1.Display();
cin.get();
return 0;
}

这里有几个问题,但让我从您提出的问题开始。

为什么输出是这样的:

Name :Jimmy Neutron Age :4194304 Weight :0.000000 Kg – Udesh

原因是每次将这样的值分配给对象时,即h1

h1 = 23; //It will assign 23 in Age
h1 = 67.45f; //It will assign 67.45 in Weight
h1 = "Jimmy Neutron";

这就是幕后发生的事情,move assignment operator被调用。

h1.operator=(Human(23));
h1.operator=(Human(67.4499969f));
h1.operator=(Human("Jimmy Neutron"));

所以,每次写其中一个时,其他两个参数都会被覆盖
若要了解问题,请尝试在每次赋值语句后使用显示函数并查看输出。

现在让我们来谈谈其他问题。

  1. 请避免使用char arraychar pointer。出于同样的目的,我们有很棒的std::string,请使用它。IIRC,每个主要编译器都会警告字符串从字面到字符的转换
  2. 我不知道你是否意识到了,但你的一个构造函数中使用int的参数名称是AGE,但你正在分配age
  3. 请避免使用不推荐使用的函数-[提示:gets]

最新更新