[英]A very strange C++ behavior
當我嘗試制造DX11引擎時,我遇到了一個非常奇怪的問題。 我找不到任何問題。 因此,我決定制作一些更簡單的代碼,並嘗試獲得相同的錯誤。 這個:
Source.cpp
#include <iostream>
#include "Header.h"
using namespace std;
struct1 g_struct1(12);
struct2 g_struct2(&g_struct1);
int main()
{
cout << "Value of g_struct1.num: " << g_struct1.num << endl;
cout << "Value of g_struct2.copynum: " << g_struct2.copynum << endl;
getchar();
return 0;
}
標頭
#ifndef _HEADER_H_
#define _HEADER_H_
#include "Header1.h"
#include "Header2.h"
#endif
Source1.cpp
#include "Header1.h"
struct1::struct1(int number)
{
num = number;
};
頭文件1.h
#ifndef _HEADER1_H_
#define _HEADER1_H_
#include "Header1.h"
#include "Header2.h"
struct struct1
{
struct1(int number);
int num;
};
#endif
Source2.cpp
#include "Header2.h"
struct2::struct2(struct1 *par1)
{
copynum = par1->num;
};
Header2.h
#ifndef _HEADER2_H_
#define _HEADER2_H_
#include "Header1.h"
#include "Header2.h"
struct struct2
{
struct2(struct1 *par1);
int copynum;
};
#endif
錯誤
1>------ Build started: Project: ConsoleApplication1, Configuration: Debug Win32 ------
1> Source.cpp
1>c:\users\<My Username>\desktop\consoleapplication1\consoleapplication1\header2.h(10): error C2061: syntax error : identifier 'struct1'
1>c:\users\<My Username>\desktop\consoleapplication1\consoleapplication1\source.cpp(8): error C2664: 'struct2::struct2(const struct2 &)' : cannot convert argument 1 from 'struct1 *' to 'const struct2 &'
1> Reason: cannot convert from 'struct1 *' to 'const struct2'
1> No constructor could take the source type, or constructor overload resolution was ambiguous
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
當然,第二個錯誤無關緊要,因為編譯器認為它是一個副本構造函數。
如果我將struct2::struct2(struct1 *par1)
更改為struct2::struct2(void *par1)
,然后將void *par1
為struct1*
,則效果很好。
好吧,如果你走了這么遠,謝謝。 對不起,英語不好。
您的標頭具有循環依賴關系。 他們甚至包括他們自己,這很愚蠢。 最終結果是兩個標頭均未得到正確處理。
在Header1
刪除兩個#include
行。 在Header2
刪除#include "Header2.h"
。 這應該可以解決問題。
它不起作用,因為在struct2的定義期間未定義struct1,並且您在構造中使用了未定義的struct poniter。
只需解決將是
struct struct2
{
struct2(struct struct1 *par1); // note the struct struct1 *
int copynum;
};
另外,如果您確實使用了Header2.h,那么您不必依賴Header2.h中的Header1.h(但您必須在Source2.cpp中)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.