c++ - '未定义对 Class::method() 的引用'

标签 c++ class methods header instance

最近我一直在学习如何在类中创建方法,这样我只需要编写一次方法,对于我实例化的每个类,我可以调用一个方法,它只对对象的变量起作用调用它,我知道如何在仅使用 main.cpp 且不使用 header 时执行此操作,但是当我使用类 header 和 cpp 时,我对如何编写它感到困惑。
我有一个类似于我想要实现的代码示例:

#include <iostream>

using namespace::std;

class Object
{
public:
    int stuff;
    void manageStuff();
    Object();
};
void Object::manageStuff()
{
    stuff++;
}

Object::Object() : stuff(0) {}

Object object1, object2;

int main() {
  for (int i = 0; i < 10; i++)
  {
      object1.manageStuff();
      object2.manageStuff();
      cout << object1.stuff << "\n";
      cout << object2.stuff << "\n";
  }
}  

这很好用,允许我有两个 Object 实例和一个对每个实例独立工作的方法,这是我当前的项目:
main.cpp :

#include <iostream>
#include "Test.h"

using namespace std;

int main()
{

    Test test;

    for (int i = 0; i < 10; i++)
    {
        test.count(); // Here's my error "undefined reference to Test::count"
    }

    return 0;
}  

测试.cpp

#include <iostream>
#include "Test.h"

using namespace std;

Test::Test()
{
    //ctor
}

Test::~Test()
{
    //dtor
}  

测试.h

#include <iostream>

#ifndef TEST_H
#define TEST_H


class Test
{
    public:
        Test();
        virtual ~Test();
        void count();
        int counter();
};

#endif // TEST_H  

最后是 TestFunctions.h

#include <iostream>
#include "Test.h"

#ifndef TESTFUNCTIONS_H_INCLUDED
#define TESTFUNCTIONS_H_INCLUDED

void Test::count()
{
    Test::counter++;
    std::cout << Test::counter;
}

#endif // TESTFUNCTIONS_H_INCLUDED  

我敢肯定,对于经验丰富的程序员来说,肯定会有一些非常明显的错误,而且我看起来有点厚,但我们将不胜感激
谢谢!

最佳答案

我建议删除 TestFunctions.h,并将 Test::count() 的实现添加到 Test.cpp。目前,TestFunctions.h header 未包含在任何地方,因此您无法访问 main 中的定义。

关于c++ - '未定义对 Class::method() 的引用',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11737853/

相关文章:

c++ - 使用 gzread 读取直到 EOF 并膨胀浮点值

methods - 求解线性方程组的并行迭代算法

javascript - 通过 .prototype 添加到对象的方法没有被继承?

ruby - .match 方法如何与其参数相关?

c++ - 在 C++ 中使用带参数的 Fortran90 子例程

c++ - ptr->ai_family 与 AF_INET 相比有何作用

c++ - libgomp缺少: install c++ compiler in home directory?

c++ - 仅允许某些派生类访问基类的成员函数

C++基类析构函数顺序问题

c++ - vector 、指针、类和 EoF 循环 (C++)