2016-01-20 95 views
1

當我嘗試編譯main.cpp時,出現「未在此範圍內聲明的節流閥」錯誤。我對C++非常陌生,所以請耐心等待。我在頭兩個cpp文件的#include "throttle.h",所以我不知道爲什麼,當我嘗試創建一個油門對象不宣...未在範圍內聲明的類

的main.cpp文件:

#include <stdio.h> 
#include "throttle.h" 

using namespace std; 
int main(int argc, char **argv) 
{ 
throttle throt1(5, 0); 
throttle throt2(4, 0); 
return 0; 
} 

油門.h文件中:

#ifndef MAIN_SAVITCH_THROTTLE 
#define MAIN_SAVITCH_THROTTLE  

namespace main_savitch_2A 
{ 
class throttle 
{ 
public: 
    // CONSTRUCTORS 
    //throttle(); 
    //throttle(int size); 
    throttle(int size = 1, int start = 0); //by adding this default 
              //constructor the other two 
              //are not needed 
    // MODIFICATION MEMBER FUNCTIONS 
    void shut_off() { position = 0; } 
    void shift(int amount); 
    // CONSTANT MEMBER FUNCTIONS 
    double flow() const 
    { 
     return position/double(top_position); 
     } 

    bool is_on() const 
    { 
     return (position > 0); 
    } 

    int get_top_position()const; 
    int get_position()const; 

    friend bool operator <(const throttle& throt1, const throttle& throt2); 
    //postcondtion: returns true if flow of throt1 < flow of throt2. 
    //return false if flow of throt1 > flow of throt2 

private: 
    int top_position; 
    int position; 
}; 
} 
#endif 

throttle.cpp文件:

#include <cassert>  // Provides assert 
#include "throttle.h" // Provides the throttle class definition 
using namespace std; // Allows all Standard Library items to be used 

namespace main_savitch_2A 
{ 

//throttle::throttle() 
//{ // A simple on-off throttle 
    //top_position = 1; 
    //position = 0; 
//} 

//throttle::throttle(int size) 
// Library facilities used: cassert 
//{ 
    //assert(size > 0); 
    //top_position = size; 
    //position = 0; 
//} 

throttle::throttle(int size, int start) 
{ 
    assert(size > 0); 
    assert(start = 0); 
    top_position = size; 
    position = start; 
} 

void throttle::shift(int amount) 
{ 
position += amount; 

if (position < 0) 
    position = 0; 
else if (position > top_position) 
    position = top_position; 
} 

bool operator <(const throttle& throt1, const throttle& throt2) 
{ 
    return(throt1.flow() < throt2.flow()); 
} 

int throttle::get_top_position()const 
{ 
    return top_position; 
} 

int throttle::get_position()const 
{ 
    return position; 

} 
} 
+0

或者在main.cpp中使用'namespace main_savitch_2A ;'。 – smkanadl

+0

哦,我明白了,因爲這是在.h文件和cpp中指定的命名空間。謝謝! –

+0

一個無關的問題:如何調用main.cpp文件中.h文件中建立的布爾運算符?或者它應該在throttle.cpp文件中執行?因爲現在它不是 –

回答

3

在你的主,它應該是main_savitch_2A::throttle throt1(5, 0);
throt2相同。

查看namespaces瞭解更多詳情。

+0

這工作以及謝謝! –

+0

一個無關的問題:我如何調用main.cpp文件中.h文件中建立的布爾運算符?或者它應該在throttle.cpp文件中執行?因爲現在它不是。 –