c++ - 这个成员函数没有被调用,我不知道如何纠正它

标签 c++

<分区>

我正在通读我的 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 页。

谢谢

最佳答案

它永远不会被调用,因为你永远不会调用它。

在这个特定的例子中,唯一设置成员变量x 的地方是在构造函数中。构造函数恰好直接这样做,而不是通过调用 setValue()

可以稍后调用setValue() 来更改x,但目前您不能。

提供对成为类(class)的一部分有意义的功能并不少见,即使您还没有完全使用该功能。不过,除非您正在编写一个库,否则您通常不会编写太多您还不需要的功能。

也许教科书后面的练习涉及调用 setValue()。我会继续阅读而不用担心这个。

关于c++ - 这个成员函数没有被调用,我不知道如何纠正它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57695848/

相关文章:

c++ - 从priority_queue c++删除使用 "top"出队的元素

c++ - 将项目文件夹(lua)嵌入到exe中

c++ - 在传递给 std::result_of 之前衰减类型

c++ - 在 STL 容器中存储属性?

c++ - 有效地从文本文件中读取带有字符串索引的巨大二维数组(矩阵)

c++ - Winapi shell 扩展覆盖 Windows 命令

c++ - 没有着色器的 OpenGL 实例化渲染

c++ - 为什么 boost::spirit 将 foo123 与 (+alpha | +alnum) 语法匹配?

python - 使用 pybind11 将抽象类作为参数作为参数传递

c++ - 链表追加方法