相关疑难解决方法(0)

头文件中的多重定义

鉴于此代码示例:

complex.h:

#ifndef COMPLEX_H
#define COMPLEX_H

#include <iostream>

class Complex
{
public:
   Complex(float Real, float Imaginary);

   float real() const { return m_Real; };

private:
   friend std::ostream& operator<<(std::ostream& o, const Complex& Cplx);

   float m_Real;
   float m_Imaginary;
};

std::ostream& operator<<(std::ostream& o, const Complex& Cplx) {
   return o << Cplx.m_Real << " i" << Cplx.m_Imaginary;
}
#endif // COMPLEX_H
Run Code Online (Sandbox Code Playgroud)

complex.cpp:

#include "complex.h"

Complex::Complex(float Real, float Imaginary) {
   m_Real = Real;
   m_Imaginary = Imaginary;
}
Run Code Online (Sandbox Code Playgroud)

main.cpp:

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

int main()
{
   Complex …
Run Code Online (Sandbox Code Playgroud)

c++ header-files

31
推荐指数
3
解决办法
2万
查看次数

为什么在头文件中定义函数会产生多个定义错误,而不是类?

这个问题建立在这两个 stackoverflow 帖子的基础上:

问题是:为什么类/结构/枚举不会出现多重定义错误?为什么它只适用于函数或变量?

我写了一些示例代码来试图解决我的困惑。有 4 个文件:namespace.h、test.h、test.cpp 和 main.cpp。第一个文件包含在 test.cpp 和 main.cpp 中,如果取消注释正确的行,则会导致多重定义错误。

// namespace.h
#ifndef NAMESPACE_H
#define NAMESPACE_H

namespace NamespaceTest {
    // 1. Function in namespace: must be declaration, not defintion
    int test(); // GOOD

    // int test() { // BAD
    //    return 5;
    //}

    // 2. Classes can live in header file with full implementation
    // But if the function is defined outside of the struct, it causes compiler error
    struct TestStruct {
        int x; …
Run Code Online (Sandbox Code Playgroud)

c++ namespaces g++

5
推荐指数
1
解决办法
1445
查看次数

标签 统计

c++ ×2

g++ ×1

header-files ×1

namespaces ×1