读书人

二个C++专有运算符

发布时间: 2013-06-25 23:45:42 作者: rapoo

2个C++专有运算符
成员对象选择 .*
成员指针选择 ->*



#include <iostream>

using namespace std;

class CStudent
{
public:
int *age;

CStudent()
{
age = new int(18);
}

~CStudent()
{
delete age;
age = NULL;
}
};

int main()
{
CStudent std1;
CStudent *pStd = &std1;

cout << *std1.age << endl;
cout << *pStd->age << endl;

//cout << std1.*age << endl;
//cout << pStd->*age << endl;

return 0;
}



如上2个注释的地方都不对,请问该怎么用啊!! C++
[解决办法]

class Testpm {
public:
void m_func1() { cout << "m_func1\n"; }
int m_num;
};

// Define derived types pmfn and pmd.
// These types are pointers to members m_func1() and
// m_num, respectively.
void (Testpm::*pmfn)() = &Testpm::m_func1;
int Testpm::*pmd = &Testpm::m_num;

int main() {
Testpm ATestpm;
Testpm *pTestpm = new Testpm;

// Access the member function
(ATestpm.*pmfn)();
(pTestpm->*pmfn)(); // Parentheses required since * binds
// less tightly than the function call.

// Access the member data
ATestpm.*pmd = 1;
pTestpm->*pmd = 2;

cout << ATestpm.*pmd << endl
<< pTestpm->*pmd << endl;
delete pTestpm;
}
来自:http://forums.codeguru.com/showthread.php?451429-Member-pointer-selector-issues
[解决办法]
C++ 成员指针?
CStudent std1;
CStudent *pStd = &std1;
int* CStudent::*page = &CStudent::age;
cout << *(std1.*page) << endl;
cout << *(pStd->*page) << endl;

读书人网 >C++

热点推荐