我想从“ takeSnapshots”类中创建对象,该对象在实例化后将学习“ lock”类中另一个对象的名称,以便当“ lock”对象的状态改变时可以稍后查询。我可以想到多种让类“ takeSnapshots”中的对象知道要查询的对象的方式(例如,将“ lock”对象的名称作为对其成员函数的调用的一部分)。但是,我认为最好一开始就处理好关系,以后再担心是否调用了正确的对象组合。
所包含的代码显示了两个类的简化版本以及在main中创建的示例实例。 我已经在它们各自的提示之后的每一行中包含了输出。 我所期望的是,“ takeSnapshots”的构造函数将存储“ lock”对象的地址。然后我可以在以后拍摄快照时使用它。您可以看到,存储的内容(至少当我使用它获取numWheels时)与“锁定”对象认为它具有numWheels的地址有一些距离。
我最想知道为什么这段代码不能按我期望的方式工作,也就是说,如果这不是一个好的架构思想,那是一回事。但是鉴于我在这里看到的行为,我显然不准备在任何复杂的情况下使用指针,并且我不想因为错误的实现而放弃基本架构。任何帮助将不胜感激。
// simpleTest.cpp : Demonstrates problem I'm having understanding
// pointer to an object.
#include "stdafx.h"
#include<iostream>
using namespace std;
class lock {
public: //Just while I run a test.
int numWheels;
lock(int numW) {
numWheels = numW;
cout << " \n In \"lock\" constuctor, address and value of numWheels
" << &numWheels << " " << numWheels << endl;
} //Values from console: 0034F874 and 4
};
class takeSnapshots {
lock* localLock;
public:
takeSnapshots(lock myLock) {
localLock = &myLock;
cout << " \n In \"takeSnapshots\" constuctor, address and value of
numWheels " << &localLock->numWheels << " "
<< localLock->numWheels << endl;
//Values from console: 0034F794 and 4 "Same value, but not the same
//address as expected from "lock."
}
void takeASnapSnapshot() {
cout << " \n When taking a snapshot, address and value of numWheels
" << &localLock->numWheels << " " << localLock->numWheels <<
endl;
//Values from console: 0034F794 and 2303449 "No longer even the
// same value as expected from "lock."
}
};
int main()
{
lock yourLock(4);
takeSnapshots myShots1(yourLock);
cout << " \n In main (from \"yourLock\"), address and value of
numWheels " << &yourLock.numWheels << " " << yourLock.numWheels <<
endl;
//Values from console: 0034F874 and 4 "Still the same values as set
//in the constructor of "lock."
//Take a picture
myShots1.takeASnapSnapshot();
return 0;
}