簡體   English   中英

C ++無法定義虛函數OUTSIDE類和頭文件

[英]C++ can't define virtual function OUTSIDE classes and header file

由於函數名稱已經在頭文件中聲明: function.h和頭文件已預加載到OJ中,因此我需要在main.cpp (也稱為OUTSIDE類)定義myAdd 但是,我可以在網上找到大多數關於虛函數的教程,只是定義該函數在類內部應執行的操作。這是頭文件:

#ifndef _FUNCTION_H_
#define _FUNCTION_H_
class abstractAdd
{
public:
    abstractAdd(){};
    ~abstractAdd(){};
    virtual int myAdd(int a, int b) = 0;

};

class Implement  : public abstractAdd
{
private:

public:
    Implement();
    ~Implement();

    int myAdd(int a,int b);

};
;

#endif

我已經在main.cpp嘗試過

//include every libraries needed
#include "function.h"

int Implement::myAdd(int a,int b)
{
    int c=a+b;
    return c;

}

int main(){
    abstractAdd& ra = *new Implement();
    string input;
    while(getline(std::cin, input)){
        istringstream testcase(input);
        int a,b;
        testcase >> a;
        testcase >> b;
        cout << ra.myAdd(a,b) << endl;
    }

    return 0;
    }

但是編譯器說:

Undefined symbols for architecture x86_64:
  "Implement::Implement()", referenced from:
      _main in cc3KANpW.o
ld: symbol(s) not found for architecture x86_64
collect2: error: ld returned 1 exit status

如何實現OUTSIDE類和頭文件功能?

new Implement()將創建一個對象。 這需要調用構造函數。 您聲明了一個構造函數Implement(); ,但未在任何地方定義它。

所以鏈接器抱怨因為找不到構造器定義

如果僅希望使用默認構造函數作為編譯器對其進行定義,則可以如下聲明:

Implement() = default;

它是默認值,並且是內聯定義的。

Implement的析構函數也是如此。


順便說一句,盡管您的程序很小並且可能是托管的,但它仍然包含泄漏。 您用new分配,但不delete創建的對象。 在實際的生產代碼中,這是不可接受的。 您可以使用智能指針簡化代碼並擺脫這種擔憂:

std::unique_ptr<abstractAdd> ra = std::make_unique<Implement>();

現在,隨着時間的推移,對象已被正確處理,您還應該將abstractAdd的析構函數也設為虛擬。 因為現在您正在多態破壞對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM