C++/Data Type/pointer
Содержание
Creating a Stray Pointer
<source lang="cpp"> typedef unsigned short int USHORT;
- include <iostream>
int main() {
USHORT * pInt = new USHORT; *pInt = 10; std::cout << "*pInt: " << *pInt << std::endl; delete pInt; long * pLong = new long; *pLong = 90000; std::cout << "*pLong: " << *pLong << std::endl; *pInt = 20; std::cout << "*pInt: " << *pInt << std::endl; std::cout << "*pLong: " << *pLong << std::endl; delete pLong; return 0;
}
</source>
Demonstrating Passing by Value
<source lang="cpp">
- include <iostream>
using namespace std; void swap(int x, int y); int main() {
int x = 5, y = 10; cout << "Main. Before swap, x: " << x << " y: " << y << endl; swap(x,y); cout << "Main. After swap, x: " << x << " y: " << y << endl; return 0;
} void swap (int x, int y) {
int temp; cout << "Swap. Before swap, x: " << x << " y: " << y << endl; temp = x; x = y; y = temp; cout << "Swap. After swap, x: " << x << " y: " << y << endl;
}
</source>
Passing Pointer to a Constant Object
<source lang="cpp">
- include <iostream>
using namespace std; class SimpleCat {
public: SimpleCat(); SimpleCat(SimpleCat&); ~SimpleCat(); int GetAge() const { return itsAge; } void SetAge(int age) { itsAge = age; } private: int itsAge;
}; SimpleCat::SimpleCat() {
cout << "Simple Cat Constructor..." << endl; itsAge = 1;
} SimpleCat::SimpleCat(SimpleCat&) {
cout << "Simple Cat Copy Constructor..." << endl;
} SimpleCat::~SimpleCat() {
cout << "Simple Cat Destructor..." << endl;
} const SimpleCat * const FunctionTwo
(const SimpleCat * const theCat);
int main() {
cout << "Making a cat..." << endl; SimpleCat Frisky; cout << "Frisky is " ; cout << Frisky.GetAge(); cout << " years old" << endl; int age = 5; Frisky.SetAge(age); cout << "Frisky is " ; cout << Frisky.GetAge(); cout << " years old" << endl; cout << "Calling FunctionTwo..." << endl; FunctionTwo(&Frisky); cout << "Frisky is " ; cout << Frisky.GetAge(); cout << " years old" << endl; return 0;
} // functionTwo, passes a const pointer const SimpleCat * const FunctionTwo(const SimpleCat * const theCat) {
cout << "Frisky is now " << theCat->GetAge(); cout << " years old " << endl; return theCat;
}
</source>
Returning Values with Pointers
<source lang="cpp">
- include <iostream>
using namespace std; short Factor(int n, int* pSquared, int* pCubed); int main() {
int number, squared, cubed; short error; cout << "Enter a number (0 - 20): "; cin >> number; error = Factor(number, &squared, &cubed); if (!error) { cout << "number: " << number << endl; cout << "square: " << squared << endl; cout << "cubed: " << cubed << endl; } else cout << "Error encountered!!" << endl; return 0;
} short Factor(int n, int *pSquared, int *pCubed) {
short Value = 0; if (n > 20) Value = 1; else { *pSquared = n*n; *pCubed = n*n*n; Value = 0; } return Value;
}
</source>