0

Hello I'm just starting to comprehend using classes in C++. Can't seem to get this simple program to work.

I get the error:

main.obj : error LNK2019: unresolved external symbol "public: int __thiscall functions::add(int,int)" (?add@functions@@QAEHHH@Z) referenced in function _wmain
1>c:\users\brr\documents\visual studio 2012\Projects\ConsoleApplication4\Debug\ConsoleApplication4.exe : fatal error LNK1120: 1 unresolved externals

My code is as follows:

main.cpp:

// ConsoleApplication4.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "functions.h"
#include <iostream>

int _tmain(int argc, _TCHAR* argv[])
{
    bool running = true;

    while(running)
    {
        functions func;
        int var1, var2;
        int option = 0;
        switch (option)
        {
        case(1):
            std::cin >> var1 >> var2;
            func.add(var1,var2);



        }


    }
    return 0;
}

functions.cpp:

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


functions::functions(void)
{
}


functions::~functions(void)
{
}

int add(int var1,int var2){
    int r;
    r = var1 + var2;
    return r;

}

functions.h:

#pragma once
class functions
{
public:
    functions(void);
    ~functions(void);
    int add(int var1,int var2);
};
4

2 回答 2

2
int functions::add(int var1,int var2){
    int r;
    r = var1 + var2;
    return r;

}

您的实现functions.cpp应该如上所示。在您当前的实现add中是一个全局函数。

所以你functions.cpp必须看起来像:

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


functions::functions(void)
{
}


functions::~functions(void)
{
}

int functions::add(int var1,int var2){
    int r;
    r = var1 + var2;
    return r;

}
于 2013-03-18T07:06:54.437 回答
0

因为,你add是一个全球性的声明。您可以在 main.cpp:: 中使用它

int Result ;
switch (option)
    {
    case(1):
        std::cin >> var1 >> var2;
        Result = add(var1,var2);
    }

否则@Aniket 为您提供了解决方案。

于 2013-03-18T07:11:22.467 回答