我正在为家庭作业编写一些课程,我希望我的班级成员函数不可能在main中调用。如果是,我希望程序退出。我如何知道何时调用我的成员函数?至于类,每个对象表示格式为< 100,200,215>的颜色。谢谢您的帮助!
class Color{
public:
Color( unsigned red = 0, unsigned green = 0, unsigned blue = 0 ); // ctor
unsigned getRed() const; // accessor
unsigned getGreen() const; // accessor
unsigned getBlue() const; // accessor
Color & setRed( unsigned red ); // mutator
Color & setGreen( unsigned green ); // mutator
Color & setBlue( unsigned blue ); // mutator
const Color & output() const;
private:
unsigned myRed;
unsigned myGreen;
unsigned myBlue;
static unsigned okColor(unsigned color);
}; //Class Color
int main(int argc, const char * argv[])
{
}
Color::Color( unsigned red, unsigned green, unsigned blue):
myRed(okColor(red)),myGreen(okColor(green)),myBlue(okColor(blue))
{
//initialization list here...
}
//accessors
unsigned Color::getRed() const {return myRed;}
unsigned Color::getGreen() const {return myGreen;}
unsigned Color::getBlue() const {return myBlue;}
//mutators
Color & Color::setRed(unsigned red){
myRed = okColor(red);
return *this;
}
Color & Color::setGreen(unsigned green){
myGreen = okColor(green);
return *this;
}
Color & Color::setBlue(unsigned blue){
myBlue = okColor(blue);
return *this;
}
//output
const Color & Color::output() const{
cout << "<" << myRed << "," << myGreen << "," << myBlue << ">" << endl;
return *this;
}
//checkers
unsigned Color::okColor(unsigned myColor){
if (myColor > 255) {
die("Color intensity is out of range!");
}
return myColor;
}
bool die(const string & msg){
cerr << endl << "Fatal error: " << msg <<endl;
exit(EXIT_FAILURE);
}
Color mixture( const Color & color0, const Color & color1, double weight){
double color1Multiplier = 0;
Color mixture;
unsigned mixtureRed;
unsigned mixtureBlue;
unsigned mixtureGreen;
color1Multiplier = 1 - weight;
mixtureRed = (color0.getRed() * weight) + (color1.getRed() * color1Multiplier);
mixtureBlue = (color0.getBlue() * weight) + (color1.getBlue() * color1Multiplier);
mixtureGreen = (color0.getGreen() * weight) + (color1.getGreen() * color1Multiplier);
mixture.setRed(mixtureRed);
mixture.setBlue(mixtureBlue);
mixture.setGreen(mixtureGreen);
return mixture;
}
答案 0 :(得分:2)
防止从main调用类很简单。不要在main
中创建课程 - 没有课程 - &gt;无法调用成员函数(除非它们是静态的)。您还可以将类标题的#include
移动到与main
不在同一来源的某个文件中。
不幸的是,没有(简单和/或可移植)的方法来确定哪个函数调用了你的代码[特别是如果我们记住现代编译器经常移动代码,所以尽管你的代码正在调用mixture
从main开始,编译器决定将其移动到main
,因为这会使它更快,更小或编译器具有内联函数的任何其他目标]。
除此之外,没有办法阻止从任何有权访问该对象的函数调用函数。对于函数的几乎每个方面,main
与其他函数没有区别。唯一的区别是从C ++运行时库调用main
。但编译器并不关心您的函数是否被称为main
,kerflunk
或fred
。
答案 1 :(得分:0)
如果您创建一个全局对象,它将在main
之前初始化,并在main
退出后销毁。
您可以使用此事实来设置标记并按照您的意愿行事。