簡體   English   中英

如何在另一個 cpp 文件中使用 const 對

[英]How to use a const pair from one cpp file in another

我有 2 個結構:S 和 R。R 有一個 S 類型的實例。在 S 中定義了一個常量對,我也想在 R 中使用它,但出現以下錯誤。 S.hpp:11:12: 錯誤:重新定義'const conf n1::n2::def1' 11 | const conf def1 = std::make_pair(10, 2); | ^~~~

這些是結構和主要功能

    #include <string>
    #include <iostream>
    #include <utility>
    #include <memory>
    
    namespace n1
    {
    namespace n2 
    {
    typedef std::pair<uint32_t, uint32_t> conf;
    const conf def1 = std::make_pair(10, 2);
    const conf def2 = std::make_pair(20, 4);
    
    struct S 
    {
        int x;
        inline void print();
    };
    using Sptr = std::shared_ptr<S>;
    }
    } 

    #include "S.hpp"
    namespace n1
    {
    namespace n2
    {
    void S::print()
    {
        std::cout<<"S-print\n";
    }
    
    }
    }

    include "S.hpp"
    #include <memory>
    
    namespace n1 
    {
    namespace c1 
    {
    struct R 
    {
        R(n1::n2::Sptr s);
        void r();
        n1::n2::Sptr s_;
        
    };
    
    } 
    }

#include "R.hpp"

namespace n1
{
namespace c1
{
R::R(n1::n2::Sptr s):s_(s)
{}

void R::r()
{
    n1::n2::conf c;
    std::cout<<"---s.first: " << c.first;
}

}
}

#include <iostream>
#include "R.cpp"
#include "S.cpp"
#include <memory>




int main()
{
    auto s = std::make_shared<n1::n2::S>();
    auto r = std::make_shared<n1::c1::R>(s);
    r->r();
    s.print();

    return 0;
}

    

我在您的程序中進行了 3 處更改,它可以編譯:

改變 1

添加了標題守衛。 這是我的習慣(和建議),每當我在標題中看不到時添加標題防護。 所以現在你的標題看起來像:

hpp

 #ifndef S_H
 #define S_H
  #include <string>
    #include <iostream>
    #include <utility>
    #include <memory>
    
    namespace n1
    {
    namespace n2 
    {
    typedef std::pair<uint32_t, uint32_t> conf;
    const conf def1 = std::make_pair(10, 2);
    const conf def2 = std::make_pair(20, 4);
    
    struct S 
    {
        int x;
        inline void print();
    };
    using Sptr = std::shared_ptr<S>;
    }
    }
    
    #endif

hpp

#ifndef R_H 
#define R_H
#include "S.hpp"
    #include <memory>
    
    namespace n1 
    {
    namespace c1 
    {
    struct R 
    {
        R(n1::n2::Sptr s);
        void r();
        n1::n2::Sptr s_;
        
    };
    
    } 
    }
    #endif

變化 2

在main.cpp中我已經改變#include "R.cpp"#include "S.cpp"#include "R.hpp"#include "S.hpp"分別。 所以你的 main.cpp 現在看起來像:

主程序

#include <iostream>
#include "R.hpp"
#include "S.hpp"
#include <memory>

int main()
{
    auto s = std::make_shared<n1::n2::S>();
    auto r = std::make_shared<n1::c1::R>(s);
    r->r();
    //s.print();

    return 0;
}

變化 3

注意在 main.cpp 中,我已經評論了我們的語句s.print(); 因為sshared_ptr類型,它沒有打印方法。

現在程序編譯,並給出輸出可以看出這里

暫無
暫無

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

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