簡體   English   中英

我是否正確使用頭文件?

[英]Am I using header files correctly?

我想學習C ++中的頭文件,因此我實現了簡單的算法,並且想知道這是否是執行此操作的正確方法。 謝謝!

my_math.h

#pragma once

namespace math {    
    /**
     * returns the sum of numbers a and b
     * @param a the first number
     * @param b the second number
     * @return sum a + b
     */
    double sum(double a, double b);

    /**
     * returns the difference of numbers a and b
     * @param a the first number
     * @param b the second number
     * @return difference a - b
     */
    double difference(double a, double b);

    /**
     * returns the product of numbers a and b
     * @param a the first number
     * @param b the second number
     * @return product a * b
     */
    double product(double a, double b);

     /**
     * returns the dividen of numbers a and b
     * @param a the first number
     * @param b the second number
     * @return dividen a / b
     */
    double divide(double a, double b);
}

my_math.cpp


#include "my_math.h"

namespace math {
double sum(double a, double b) { return a + b; }
double difference(double a, double b) { return a - b; }
double product(double a, double b) { return a * b; }
double divide(double a, double b) { return a / b; }
}

main.cpp中


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

using namespace std;
using namespace math;

int main() {
    cout << sum(4, 6) << endl;
    cout << difference(4, 6) << endl;
    cout << product(4, 6) << endl;
    cout << divide(24, 6) << endl;
}

我應該放嗎

 namespace math { 

在源文件和頭文件中? 在頭文件中實現沒有類的函數也是一種好習慣嗎?

我應該放嗎

 namespace math { 

在源文件和頭文件中?

當實現my_math.h中聲明的函數之一時,必須向編譯器指示該函數位於math名稱空間中。 有兩種方法可以做到這一點:

方法1

做完了。

方法2

在每個函數實現中使用math::范圍。

#include "my_math.h"

double math::sum(double a, double b) { return a + b; }
double math::difference(double a, double b) { return a - b; }
double math::product(double a, double b) { return a * b; }
double math::divide(double a, double b) { return a / b; }

就編譯器而言,這兩種方法完全相同。 您可以使用任何一種方法。 您甚至可以將兩者混合使用。 沒有什么不妥。

在頭文件中實現沒有類的函數也是一種好習慣嗎?

這個問題的答案是相當廣泛的。 這不是解決它的最佳位置。

暫無
暫無

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

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