c++ cdi+示例
C ++中的本地類 (Local Class in C++)
In C++, generally a class is declared outside of the main() function, which is global for the program and all functions can access that class i.e. the scope of such class is global.
在C ++中,通常在main()函數外部聲明一個類,該類對于程序是全局的,并且所有函數都可以訪問該類,即此類的范圍是全局的。
A local class is declared inside any function (including main() i.e. we can also declare a class within the main() function) and the scope of local class is local to that function only i.e. a local class is accessible within the same function only in which class is declared.
本地類在任何函數內聲明(包括main(),即我們也可以在main()函數內聲明一個類),并且本地類的范圍僅對該函數本地,即本地類只能在同一函數內訪問在哪個類中聲明。
Example:
例:
Here, we are declaring and defining two classes "Test1" and "Test2", "Test1" is declared inside a user-defined function named testFunction() and "Test2" is declares inside the main() function.
在這里,我們聲明并定義了兩個類“ Test1”和“ Test2” ,在一個名為testFunction()的用戶定義函數中聲明了“ Test1”,在main()函數中聲明了“ Test2” 。
Since classes "Test1" and "Test2" are declared within the functions, thus, their scope will be local to those functions. Hence, "Test1" and "Test2" are local classes in C++.
由于在函數中聲明了“ Test1”和“ Test2”類,因此它們的作用域對于這些函數而言是局部的。 因此, “ Test1”和“ Test2”是C ++中的本地類 。
Program:
程序:
#include <iostream>
using namespace std;
//A user defined function
void testFunction(void)
{
//declaring a local class
//which is accessible within this function only
class Test1
{
private:
int num;
public:
void setValue(int n)
{
num = n;
}
int getValue(void)
{
return num;
}
};
//any message of the function
cout<<"Inside testFunction..."<<endl;
//creating class's object
Test1 T1;
T1.setValue(100);
cout<<"Value of Test1's num: "<<T1.getValue()<<endl;
}
//Main function
int main()
{
//declaring a local class
//which is accessible within this function only
class Test2
{
private:
int num;
public:
void setValue(int n)
{
num = n;
}
int getValue(void)
{
return num;
}
};
//calling testFunction
cout<<"Calling testFunction..."<<endl;
testFunction();
//any message of the function
cout<<"Inside main()..."<<endl;
//creating class's object
Test2 T2;
T2.setValue(200);
cout<<"Value of Test2's num: "<<T2.getValue()<<endl;
return 0;
}
Output
輸出量
Calling testFunction...
Inside testFunction...
Value of Test1's num: 100
Inside main()...
Value of Test2's num: 200
翻譯自: https://www.includehelp.com/cpp-programs/local-class-with-example.aspx
c++ cdi+示例