本文共 3031 字,大约阅读时间需要 10 分钟。
c ++查找字符串
Program 1:
程序1:
#includeusing namespace std;class Sample { int X; int* PTR = &X;public: void set(int x) const; void print();};void Sample::set(int x) const{ *PTR = x;}void Sample::print(){ cout << *PTR - EOF << " ";}int main(){ Sample OB; Sample* S = &OB; S->set(10); S->print(); return 0;}
Output:
输出:
11
Explanation:
说明:
In the above program, we created class Sample that contain member X and a constant pointer PTR that contains the address of X, here we cannot relocate the pointer but we can change the value of X using pointer PTR.
在上面的程序,我们创建的类样品含有成员X和包含X的地址,在这里我们不能搬迁的指针,但我们可以用指针PTR改变X的值恒定的指针PTR。
Here, we defined two set() and print() outside the class.
在这里,我们在类外部定义了两个 set()和print() 。
Here, set() is a const member function, but we can assign value using pointer variable in set() function.
这里, set()是const成员函数,但是我们可以在set()函数中使用指针变量来赋值。
In the main() function, we created object of class and created pointer initialized with object OB, and print() member function uses .
在main()函数中,我们创建了class对象,并创建了用对象OB初始化的指针,而print()成员函数使用 。
cout<< *PTR-EOF <<" ";
The value of EOF is -1 then, 10- -1 = 11.
EOF的值为-1,则10- -1 = 11 。
Thus, 11 will be printed on the console screen.
因此,将在控制台屏幕上打印11 。
Program 2:
程式2:
#includeusing namespace std;class Sample {private: int* X;public: void init() { X = new int(); *X = 5; } void fun() { *X = *X * *(&(*X)) + 10; cout << *X; }};int main(){ Sample OB; OB.init(); OB.fun(); return 0;}
Output:
输出:
35
Explanation:
说明:
In the above program, we created a class Sample that contains an integer X and then we initialize pointer X in init() member function using the . And assign with value 5.
在上述程序中,我们创建了一个包含整数 X的类Sample ,然后使用在init()成员函数中初始化了指针X。 并赋值5。
Now, come to the member function fun() and evaluate the expression,
现在,进入成员函数fun()并计算表达式,
*X = *X* *(&(*X))+10;*X = 5 * 5+10;*X = 25+10;*X = 35;
Then the final value of *X is 35 that will be printed on the console screen.
然后, * X的最终值为35 ,它将在控制台屏幕上打印。
Program 3:
程式3:
#includeusing namespace std;class Sample {private: int* X; int* Y;public: void init() { X = new int(); Y = new int(); X = 10; Y = 20; } void fun() { *X = *X + *Y; cout << *X; }};int main(){ Sample OB; OB.init(); OB.fun(); return 0;}
Output:
输出:
main.cpp: In member function ‘void Sample::init()’:main.cpp:15:13: error: invalid conversion from ‘int’ to ‘int*’ [-fpermissive] X = 10; ^~main.cpp:16:13: error: invalid conversion from ‘int’ to ‘int*’ [-fpermissive] Y = 20; ^~
Explanation:
说明:
The above program will generate errors. Because in the init() member function, we assigned integer value to the pointer variable, if we want to assign value to pointer variable then we need to use like,
上面的程序将产生错误。 因为在init()成员函数中,我们为指针变量分配了整数值,所以,如果我们想为指针变量分配值,则需要使用例如
*X = 10;*Y = 20;
Recommended posts
推荐的帖子
翻译自:
c ++查找字符串
转载地址:http://tdtzd.baihongyu.com/