簡體   English   中英

Header 文件中的 C++ 類

[英]C++ classes in Header Files

我是 C++ 的真正初學者,目前的任務存在一些重大問題。 目標是在 C++ 中實現基本的 Complex 算法,但是我以前接觸過這個主題的所有視頻/網站都沒有包含我們需要用來運行測試的 a.hpp (Complex.hpp)。 但是將 Complex{...} class 添加到這個 header 文件會導致我的代碼出現幾個問題。

#ifndef H_lib_Complex
#define H_lib_Complex

namespace arithmetic {

class Complex {
    public:
    double re, im;

    Complex();                   //init Complex with (0,0)
    Complex(double r);           //init Complex with (r,0)
    Complex(double r, double i); //init Complex with (r,i)
    double real(Complex c);      //return real part of Complex
};
} #endif

我的 Complex.cpp 看起來像這樣:

#include "lib/Complex.hpp"          <- no complaining about the path
namespace arithmetic {

Complex::Complex() {
    this->re = 0;
    this->im = 0;
}
Complex::Complex(double r) {
    this->re = r;
    this->im = 0;
}
Complex::Complex(double r, double i) {
    this->re = r;
    this->im = i;
}

double Complex::real(Complex c){
    return c.re;
}

//add some more functionality like abs, norm, conj,...

} // namespace arithmetic

現在,如果我想測試我的代碼,測試文件會顯示以下錯誤消息:

#include "lib/Complex.hpp"              <-- lib/Complex.hpp: No such file or directory(gcc)
#include <cmath>
#include <sstream>
#include <gtest/gtest.h>

using namespace arithmetic;
using namespace std;

TEST(TestComplex, realImag) {
    Complex a;
    Complex b = 42.0;
    Complex c(1.0, 2.0);

    ASSERT_FLOAT_EQ(a.real(), 0);
    ...(more tests)

ASSERT_FLOAT_EQ它顯示:

#define ASSERT_FLOAT_EQ(val1,val2) ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, val1, val2) 
Expands to: 
ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, a.real(), 0)

too few arguments in function call C/C++(165)

但是如果我沒理解錯的話,這個測試收到了兩個值a.real和0,為什么還是不行呢?

real 采用 Complex 類型的參數。 我想你的意思是

double Complex::real(){ return this->re; }

也相應地更改聲明。

暫無
暫無

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

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