我正在编写一个程序来添加一个类的 2 个对象。
//program for adding 2 objects data of same class
#include<iostream>
using namespace std;
class distances
{
private:
int feet;
float inches;
public:
distances() //constructor
{
feet = 0;
inches = 0.0;
}
distances(int f, float i) //constructor
{
feet = f;
inches = i;
}
void get_data() //taking value
{
cout << "Enter the distance in feet and inches :: " << "\n";
cin >> feet >> inches;
}
void show_data() //showing data
{
cout << "The distance in feet is ::" << feet
<< " and in inches is :: " << inches;
}
void add(distances d1, distances d2); //adding to objects
};
void distances::add(distances d1, distances d2)
{
inches = d1.inches + d2.inches;
feet = 0;
while(inches >= 12)
{
inches = inches - 12;
++feet;
}
feet += d1.feet + d2.feet;
}
void main()
{
distances d1, d2, d3;
d1.get_data();
d2.get_data();
d3.add(d1, d2);
d3.show_data();
getch();
}
我的程序运行良好,但我的先生告诉我添加 2 个对象的方法是错误的,尽管他没有说明原因。他告诉我,当我添加更多对象时,我的方法将不起作用。我不知道为什么我的方法是错误的。我的朋友告诉我,我的问题可能在d3.add(d1,d2);
真的吗?
我的第二个问题是,当我使用类名、函数名和构造函数名作为距离而不是距离时,就会出现以下错误
1>c:\users\abc\documents\visual studio 2010\projects\pass\pass\pass.cpp(47): error C2872: 'distance' : ambiguous symbol
1> could be 'c:\users\abc\documents\visual studio 2010\projects\pass\pass\pass.cpp(6) : distance'
1> or 'c:\program files (x86)\microsoft visual studio 10.0\vc\include\xutility(899) : iterator_traits<_Iter>::difference_type std::distance(_InIt,_InIt)'