【发布时间】:2016-05-02 09:02:29
【问题描述】:
我正在做一个项目,我想在一个类中声明私有变量,因为我在很多地方都读到这比将它们声明为 public 更好,但是我如何在 main 中访问它们?我应该使用什么样的功能来使它们可以访问?我想通过一个不是像我所做的那样来自 main 的函数来解决系统问题。 到目前为止,这就是我的代码,
#include <iostream>
#include <limits>
using namespace std;
class Equation
{
private:
int a1, a2, b1, b2, c1, c2;
public:
};
int main()
{
int a, b, c, d, e, f;
cout << "\n" << endl;
cout << " **** Hello **** \n\n" << endl;
cout << "This is a program to solve a system of equation" << endl;
cout << "Equations will look like a1*x+b1*y=c1" << endl;
cout << "and a2*x+b2*y=c2\n" << endl;
cout << "Enter the values for the first equation \n" << endl;
while ((cout << "Enter the value of a1 :\n") && !(cin >> a))
{
cout << "Invalid input, please enter a number \n" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
while ((cout << "Enter the value of a2 :\n") && !(cin >> b))
{
cout << "Invalid input, please enter a number \n" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
while ((cout << "Enter the value of b1 :\n") && !(cin >> c))
{
cout << "Invalid input, please enter a number \n" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
while ((cout << "Enter the value of b2 :\n") && !(cin >> d))
{
cout << "Invalid input, please enter a number \n" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
while ((cout << "Enter the value of c1 :\n") && !(cin >> e))
{
cout << "Invalid input, please enter a number \n" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
while ((cout << "Enter the value of c2 :\n") && !(cin >> f))
{
cout << "Invalid input, please enter a number \n" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
cout << "The first equation is : " << a << "x" <<
"+" << c << "y" <<
"=" << e << "\n" <<
endl;
cout << "The second equation is : " << b << "x" <<
"+" << d << "y" <<
"=" << f << "\n" <<
endl;
double x = ((c * e) - (b * f)) / ((a * e) - (b * d));
double y = ((a * f) - (c * d)) / ((a * e) - (b * d));
cout << "The solution of the system is " <<
"x = " << x << "\t" <<
"y = " << y <<
"\n\n" <<endl;
cout << " **** Thank You **** " << endl;
return 0;
}
【问题讨论】:
-
我在很多地方都读到过,这比将它们公开要好,但是我如何在 main 中访问它们 -- 你创建这些变量
private的原因是您确实不希望main或任何其他外部实体访问这些变量。 -
@AndreyChernukha 你教他们如何在脚上开枪并没有帮助他们。
-
@BaummitAugen 好吧,她绝对是个菜鸟,她甚至不知道什么是 setter 和 getter。你真的认为她应该不知道他们的存在吗?她现在发现它们不好还为时过早,因为她不明白为什么。对她来说,现在熟悉他们就足够了。她明天不打算写 Windows。你不这么认为吗?
-
@GermelindaMusliaj 你还没有完全理解写一个类意味着什么。你写的这门课应该做什么?我知道这不仅仅是设置成员变量。这门课有一些目的。您可以通过编写
public成员函数来传达该目的。如果是解方程,那么你写一个成员函数来设置变量。用户并不关心你的类的内部是什么样子,只要它正在做一些设置变量的事情。然后你写一个Solve()函数来解方程。 -
@GermelindaMusliaj 如果您将类更改为使用 6 个值的数组而不是 6 个单独的变量,该怎么办?再说一次,对于我(您的班级的用户)来说,知道您在
Equation班级中使用了数组是否有意义?我为什么要在乎?只要您提供一个将一些值作为参数的“set_variables”函数,这对用户来说就是最重要的。同样,如果在以后的版本中设置变量很复杂怎么办?同样,只要用户调用“set_variables”函数,用户的代码就不会改变。只有您的内部课程代码会更改。