输入输出数组元素的函数重载
Program 1:
程序1:
#include <iostream>
using namespace std;
void print()
{
cout << "****" << endl;
}
void print(int NUM, char ch)
{
for (int i = 0; i < NUM; i++)
cout << ch;
cout << endl;
}
int main()
{
short num = 4;
print(num, '@');
return 0;
}
Output:
输出:
@@@@
Explanation:
说明:
Here, we overloaded print() function,
在这里,我们重载了print()函数,
void print();
void print(int NUM,char ch);
Declarations for overloaded print() function are given below,
下面给出了重载的print()函数的声明,
In the main() function we passed a short variable instead of int variable, then it will call the function with int argument. Because downgrading of type is possible to call overloaded function.
在main()函数中,我们传递了一个短变量而不是int变量,然后它将使用int参数调用该函数。 因为类型的降级可以调用重载函数。
Program 2:
程式2:
#include <iostream>
using namespace std;
void print()
{
cout << "****" << endl;
}
void print(short NUM, char ch)
{
for (int i = 0; i < NUM; i++)
cout << ch;
cout << endl;
}
int main()
{
int num = 4;
print(num, '@');
return 0;
}
Output:
输出:
@@@@
Explanation:
说明:
Here, we overloaded print() function.
在这里,我们重载了print()函数。
void print();
void print(short NUM,char ch);
Declarations for overloaded print() function are given below,
下面给出了重载的print()函数的声明,
In the main() function we passed int variable instead of short variable, then it will call the function with short argument. Because similar to downgrading, upgrading of type is also possible to call overloaded function.
在main()函数中,我们传递了int变量而不是short变量,然后它将使用short参数调用该函数。 因为类似于降级,类型的升级也可以调用重载函数。
Program 3:
程式3:
#include <iostream>
using namespace std;
class Test {
void print()
{
cout << "****" << endl;
}
void print(short NUM, char ch)
{
for (int i = 0; i < NUM; i++)
cout << ch;
cout << endl;
}
};
int main()
{
short num = 4;
Test T;
T.print(num, '@');
return 0;
}
Output:
输出:
main.cpp: In function ‘int main()’:
main.cpp:23:21: error: ‘void Test::print(short int, char)’ is private within this context
T.print(num, '@');
^
main.cpp:10:10: note: declared private here
void print(short NUM, char ch)
^~~~~
Explanation:
说明:
This code will generate an error because, in the class Test, we did not specify any access modifier, then by default all members functions of class Test are private. So, it will generate an error because we cannot access private members outside the class.
该代码将产生错误,因为在Test类中,我们没有指定任何访问修饰符,因此默认情况下Test类的所有成员函数都是私有的。 因此,它将产生一个错误,因为我们无法访问该类之外的私有成员。
翻译自: https://www.includehelp.com/cpp-tutorial/function-overloading-find-output-programs-set-2.aspx
输入输出数组元素的函数重载