【发布时间】:2016-01-20 22:52:00
【问题描述】:
当我尝试编译 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;
}
throttle.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;
}
}
【问题讨论】:
-
或者你 main.cpp 中的
using namespace main_savitch_2A;。 -
哦,我明白了,因为这是 .h 文件和 cpp 中指定的命名空间。谢谢!
-
一个不相关的问题:如何在main.cpp文件中调用.h文件中建立的bool运算符?还是应该在throttle.cpp 文件期间执行?因为目前还不是
-
小于运算符只有在您调用它时才会执行。例如。
auto isLess = throt1 < throt1;在你的 main.cpp 中。
标签: c++