2017-03-09 129 views
0

我寫下一個示例代碼,試圖複製我得到一個學校項目有關對象的範圍誤差不申報對象:需要幫助理解的範圍

在文件:classTest.cpp

#include "headerone.h" 
#include "headertwo.h" 

#include <iostream> 

using namespace std; 

int main() { 

    ClassOne* pntrObj1 = new ClassOne; 

    ClassTwo* pntrObj2 = new ClassTwo; 

    pntrObj1->testClassOne(); 

    return 0; 
} 

在文件:headerone.h

#ifndef HEADERONE_H 
#define HEADERONE_H 

#include "headertwo.h" 

#include <iostream> 

using namespace std; 

class ClassOne { 
    public: 
     void testClassOne() { 
      cout << "One Worked\n"; 
      pntrObj2->testClassTwo(); 
     } 
}; 

#endif 

在文件:headertwo.h

#ifndef HEADERTWO_H 
#define HEADERTWO_H 

#include <iostream> 

using namespace std; 

class ClassTwo { 
    public: 
     void testClassTwo() { 
      cout << "Two Worked"; 
     } 
}; 

#endif 

要清楚,錯誤是:pntrObj2未在此範圍內聲明。該錯誤來自文件headerone.h

如果我不得不猜測,我需要以某種方式傳遞參考,但我不知道從哪裏開始。任何幫助表示讚賞。

+1

猜測自己的方式爲C++就是要關掉它一個非常簡單的方法。你應該從一本好書開始:http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list –

回答

1

變量pntrObj2只在其聲明的範圍內可見,在這種情況下,您的函數是main()。換句話說,只有main()大括號內的代碼才能夠使用名稱pntrObj2來引用該變量。但是,您可以將該值作爲函數調用的參數傳遞給其他代碼段。

所以,也許你想要做的是添加一個參數到testClassOne()方法,所以你可以傳入值pntrObj2。因此pntrObj1->testClassOne();將變爲pntrObj1->testClassOne(pntrObj2);,並且您在其中定義testClassOne可以添加相應的參數。我會讓你摸不着頭腦,以不完全做你的功課你:)

0

在這裏,你有你的文件了大量的時間和testClassOne功能,不聲明pntrObj2

使用

insteed的
void testClassOne() { 
      cout << "One Worked\n"; 
      ClassTwo* pntrObj2 = new ClassTwo() 
      pntrObj2->testClassTwo(); 
     } 

void testClassOne() { 
      cout << "One Worked\n"; 
      pntrObj2->testClassTwo(); 
     }