<分区>
我正在通读我的 C++ 教科书,为即将到来的类(class)做准备,并完成书中的练习。这个练习编译并且似乎给出了你期望的结果,但似乎有一个错误,我不知道如何修复它。 这是代码。
// Page 706 from text
//Contents of ThisExample.h
class Example
{
int x;
public:
Example(int a){x=a;}
void setValue(int);
void printAddressAndValue();
};
/*
//Contents of ThisExample.cpp
#include "ThisExample.h"
*/
#include <iostream>
using namespace std;
/*********************************************************
* Set value of object.
*********************************************************/
void Example::setValue(int a) // <---------- Doesn't execute
{ // <---------- Doesn't execute
x = a; // <---------- Doesn't execute
} // <---------- Doesn't execute
void Example::printAddressAndValue()
{
cout<< "The object at address " << this << " has "
<< "value "<< (*this).x<<endl;
}
/*
//Contents of main program
#include <iostream>
#include "ThisExample.h"
using namespace std;
*/
int main()
{
Example ob1(10), ob2(20);
// Print the addresses of the two objects
cout<<"Addresses of objects are "<< &ob1 << " and "<<&ob2<<endl;
// Print the addresses and values from within the member function
ob1.printAddressAndValue();
ob2.printAddressAndValue();
return 0;
}
在书中,他们谈到了替换
void Example::setValue(int a)
{
x = a;
}
与
void Example::setValue(int a)
{
this->x = x;
}
但是当我使用调试器(我也是新手)单步执行它时,我看不到该函数被调用过。
我已经尝试完全注释掉该函数,但它仍在运行,这就是我知道它没有被调用的原因。
我也试过从类里面移除
Example(int a){x=a;}
但是它没有编译。有什么帮助吗?我只想跟着教科书一起走,它叫做“Starting Out With C++ Early Objects” Judy Walters、Godfrey Muganda、Tony Gaddis”,练习在第 706 页。
谢谢