简体   繁体   中英

Why am I getting a linker error?

I am getting the error: "undefined reference to 'yClass::yClass()'

when attempting to create an instance of the class in main. Anyone know why?

Header:

#ifndef header_h
#define header_h

#include <cstdlib>
#include <iostream>
using namespace std;

class yClass
{
      public:
             void one();
             void two(int,int);
             yClass();

      private:
              int a;
              int b;
};

#endif

main:

#include "header.h"

int main()
{
    yClass a;

    system("PAUSE");
    return EXIT_SUCCESS;
}

You have declared yClass's constructor, but not defined it. Or, if you have defined it in another file (ie the .cpp file that corresponds to "header.h"), then you haven't linked with that.

The constructor is used when the object in main is initialized, so its definition must be present. The "one" and "two" methods, by contrast, are never called, so definitions for them aren't actually required.

A simple fix for having never defined the constructor is to define it in the class definition:

struct yClass {
    yClass() : a(), b() {}

private:
    int a, b;
};

If the problem is you have defined the constructor but not linked with the definition, then you need to add the other translation unit ("the .cpp file") to your makefile, project, command line, etc.

因为您声明了构造函数(以及yClass的其他函数),但没有实现它们。

Where did you actually define yClass? Unless you
#include "yclass.cpp
or link in a library that contains yclass, just including the header is not enough.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM