簡體   English   中英

為什么內聯我的訪問器會破壞我的代碼?

[英]Why does inlining my accessors break my code?

我遇到一個奇怪的問題,試圖inline我的“Person”類的訪問器導致代碼無法編譯。

以下代碼將成功編譯並運行(使用Visual Studio 2012):

Person.h

#pragma once
#include <string>

using namespace std;

class Person
{
public:
    Person(string name, int age = 0);
    ~Person(void);

    // Accessors
    string name(void) const;
    int    age (void) const;

private:
    string m_name;
    int    m_age;
};

Person.cpp

#include "stdafx.h"
#include "Person.h"


Person::Person(string name, int age) :
    m_name(name),
    m_age (age )
{}


Person::~Person(void) {}

string Person::name(void) const
{
    return m_name;
}

int Person::age(void) const
{
    return m_age;
}

header_test.cpp

#include "stdafx.h"
#include <iostream>
#include "Person.h"

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    Person p("Joe");

    cout << p.name() << endl;

    return 0;
}

如果我將我的訪問者更改為 inline 函數,則代碼會中斷。

在Person.h中內聯訪問器

// Accessors
inline string name(void) const;
inline int    age (void) const;

在Person.cpp中內聯訪問器

inline string Person::name(void) const
{
    return m_name;
}

inline int Person::age(void) const
{
    return m_age;
}

這樣做會產生以下錯誤:

1> header_test.obj:錯誤LNK2019:未解析的外部符號“public:class std :: basic_string,class std :: allocator> __thiscall Person :: name(void)const”(?name @ Person @@ QBE?AV?$ basic_string @DU?$ char_traits @ D @ std @@ V?$ allocator @ D @ 2 @@ std @@ XZ)在函數_wmain中引用

1>致命錯誤LNK1120:1個未解析的外部

上帝,錯誤信息是神秘的...感謝所有這些哦有用的信息Microsoft / Visual Studio!


我知道inline關鍵字只是編譯器的“提示”,可能在這里沒有實際價值,但它仍然不應該破壞代碼!

為什么會這樣?

我不是語言律師,所以我無法判斷編譯器行為是否合法。 然而,我可以解釋發生了什么。

inline標記函數時,您並沒有暗示編譯器可以內聯此函數。 由於超過10年,編譯器不需要您的提示。 他們知道什么時候內聯。 相反,你所做的,你將函數定義指定為包含它的每個翻譯單元的本地。對於這個定義應該是可用的。

實際上你所說的是name()定義對於每個.cpp文件應該是本地的,但是你沒有為每個.cpp文件提供它! 我仍然認為編譯器可以在這里發出警告。

如果要使用inline關鍵字,則需要在標題中定義函數體。 inline也不只是給編譯器一個提示:它或多或少地關閉了“一個定義”規則*關於被定義一次且僅一次的函數。

此外,如果在頭文件中定義類成員函數,則為ala

class Foo {
    int bar() { return 5; }
};

它們默認為“內聯”,因此沒有理由輸入關鍵字:-)

*技術上沒有,但為簡單起見,您可以將其視為行為方式。 請參閱SergeyA的以下評論。

暫無
暫無

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

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