gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 00:55:44 26 4
gpt4 key购买 nike

最近我一直在学习如何在类中创建方法,这样我只需要编写一次方法,对于我实例化的每个类,我可以调用一个方法,它只对对象的变量起作用调用它,我知道如何在仅使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com